0

Is it possible to reference multiple variables with the same prefix in R? Suppose you have a series of variables (A1, A2... Ax). I would like to define a series of variables (B1, B2... Bx) in terms of the A series of variables. The following example does not work, but I would like to define B1 and B2 as five times A1 and A2, respectively.

A1 <- 5
A2 <- 10

paste0("B",1:2) <-  5 * paste0("A",1:2)

In this case, the output should be: B1=25,B2=50. Is there a way to do this?

Bjørn Kallerud
  • 979
  • 8
  • 23
  • 2
    This is an assignment problem. I do not understand why you would do this.. but anyway you can do `list2env(as.list(setNames(unlist(mget(ls(pattern='^A\\d$')))*5,paste0('B',1:2))),.GlobalEnv)` – Onyambu Sep 19 '18 at 01:12
  • now call `B1` or even`B2` – Onyambu Sep 19 '18 at 01:13
  • Can you include the expected output, it is not clear from the question. – neilfws Sep 19 '18 at 01:15
  • 2
    You shouldn't create variables with the same prefix - you should be using a vector or a list. You are just making things hard on yourself otherwise. [See here for extended discussion](https://stackoverflow.com/a/24376207/903061). – Gregor Thomas Sep 19 '18 at 01:22
  • I would do something similar to @Onyambu , `setNames(unlist(mget(paste0("A", 1:2))) * 5 , paste0("B", 1:2))` – Ronak Shah Sep 19 '18 at 01:29

1 Answers1

1

One way with sapply, assign, and get:

sapply(1:2, function(x) assign(paste0("B",x), 5*get(paste0("A", x)), pos=1))
DanY
  • 5,920
  • 1
  • 13
  • 33