0

I want to create a loop which creates new variables and uses the values of the loop sequence to name that variable. In stata this is easily done using the `x' syntax as shown below.

foreach x of 1 2 3 4 5  {
    gen newvar_`x' = `x'*1.2
}

which would produce 5 variables named

newvar_1 = 1.2
newvar_2 = 2.4
newvar_3 = 3.6
newvar_4 = 4.8
newvar_5 = 6.0

I have tried to do the following codes in r to do the same thing.

for (i in c(1,2,3,4,5)){
  newvar_i <- i*1.2
}

This produces one variable named "newvar_i" with a value of 6

And I have tried this one too.

for (i in c(1,2,3,4,5)){
  paste("newvar_",i, sep = "")  <- i*1.2
}

Which produces the following error

"Error in paste("newvar_", i, sep = "") <- i*1.2 : 
  target of assignment expands to non-language object"

Does anyone have any solutions to this problem that I am having?

user9903833
  • 137
  • 6
  • 1
    why on earth would you do this?, anyway do `list2env(as.list(setNames(1:5*1.2,paste('newvar_',1:5))),.GlobalEnv)` and now call `newvar_1` etc – Onyambu Sep 09 '18 at 08:18
  • if you want to use `for loop` then you can make good use of `assign` function. ie `for I in ….{assign(paste0('newvar_', I,),I *1.2)}` – Onyambu Sep 09 '18 at 08:22
  • 1
    R relies on a different object-oriented programming philosophy. It is best to familiarize yourself with its conventions rather than trying to translate Stata code directly. –  Sep 09 '18 at 08:27
  • **What you're trying to do sounds like a bad idea.** The R way would be to use a function from the `*apply` family to loop and store objects in a `list` (instead of creating multiple objects in your current environment). The use of `assign` is in most cases [a bad idea](https://stackoverflow.com/questions/17559390/why-is-using-assign-bad). – Maurits Evers Sep 09 '18 at 11:23

2 Answers2

1

Solution: (thank you Onyambu)

for (I in c(1,2,3,4,5)){
assign(paste0('newvar_', I),I *1.2)
}
user9903833
  • 137
  • 6
0

If you're new to R, consider this approach. Create the values as a list, name the values, and call them using the $ sign.

myVars <- as.list(1:5 * 1.2) # creates values
names(myVars) <- paste("newvar_", 1:5, sep = "") # names values

If you want to call a specific value, you use the name of your list (myVars), the $ sign, and then the name of the value. Below returns the value for newvar_1

myVars$newvar_1