0

I can make this code:

#set seed
set.seed(848)

#make variables (similar, not same)
myvar_a <- rnorm(n = 100, mean = 1, sd = 2)
myvar_b <- rnorm(n = 100, mean = 2, sd = sqrt(3))
myvar_c <- rnorm(n = 100, mean = 4, sd = sqrt(5))
myvar_d <- rnorm(n = 100, mean = 8, sd = sqrt(8))

#transform variables
for(i in 1:4){
     if(i ==1){
          myvar_1 <- myvar_a
     } else if (i==2) {
          myvar_2 <- myvar_b
     } else if (i==3) {
          myvar_3 <- myvar_b
     }  else {
          myvar_4 <- myvar_b
     } 
}

It gives me this:

enter image description here

Is there a way to do it with "paste" and the loop variable?

In MATLAB there is the eval that treats a constructed character string as a line of code, so I could create sentences then run them from within the code.

Adriaan
  • 17,741
  • 7
  • 42
  • 75
EngrStudent
  • 1,924
  • 31
  • 46
  • 2
    You can do something similar as in MatLab in R, but you shouldn't. R is an actual programming language. Use a list to store these variables. It will make subsequent steps way easier. – Roland May 11 '17 at 12:58
  • I have a stack of results in separate files from separate runs of nother program that I am going to load. They are elaborate structures, not simple data, and they all have the same name upon being loaded. When you say "list" do you mean "list of elaborate data structures"? Is the R list like the MatLab structure? – EngrStudent May 11 '17 at 13:00
  • Put them into a list as roland suggests. lists are the most general object in R and each list element can hold any other R object, regardless of what is contained in another element. So complexity of the object is irrelevant. If you use some ordered process to load the data, you can use a similar process to name your list items. See gregor's answer to [this post](http://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames) for some useful tips. – lmo May 11 '17 at 13:04
  • 2
    Dynamic variable naming is a bad idea in general, and in MATLAB using `eval` is [one of the worst practises possible](http://stackoverflow.com/questions/32467029/how-to-put-these-images-together/32467170#32467170), especially to do this. – Adriaan May 16 '17 at 17:25

2 Answers2

1
l <- list()

#transform variables
for(i in 1:4){
  if(i ==1){
    l[[paste0("myvar_", i)]] <- myvar_a
  } else if (i==2) {
    l[[paste0("myvar_", i)]] <- myvar_b
  } else if (i==3) {
    l[[paste0("myvar_", i)]] <- myvar_b
  }  else {
    l[[paste0("myvar_", i)]] <- myvar_b
  } 
}

print(l)

Of course, an experienced R user would use lapply instead of the for loop.

Roland
  • 127,288
  • 10
  • 191
  • 288
1

You can do:

for(i in 1:4){
  let <- if(i == 1) "a" else "b"
  assign(paste0("myvar_", i), get(paste0("myvar_", letters[i])))
}

But as others say, this is not really recommendable.

amatsuo_net
  • 2,409
  • 11
  • 20