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?