0

In Stata, you can create a bunch of similarly named variables, differing only in a number (Var1, Var2, ...; Vbl1, Vbl2, ...) by doing:

forvalues i = 1/30{
     generate Var`i' = %some way of generating the variable
     generate Vbl`i' = 
}

Is there a way of doing this in R? I have code that generates variables, but I'd like to streamline it. What I really want is, is there some equivalent to the `i' ? I.e. some way to define a local macro, iterate over it, and use it in variable names?

This seems like the answer to this question might help ( R equivalent of Stata's for-loop over macros ), so apologies if it's redundant.

Gregor Thomas
  • 104,719
  • 16
  • 140
  • 257
  • 1
    The R way to do this [is to use lists](https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames/24376207#24376207) and iteration functions, whether `*apply`, or `replicate` or `for` loops. You can use `assign` and `paste` and `get`, but it's asking for trouble. – Gregor Thomas Dec 02 '20 at 19:38

1 Answers1

0

If you had a data frame called df, you could do

library(glue)
for(i in 1:30){
  df[[glue("Var{i}")]] <- # some way to generate variable
  df[[glue("Vbl{i}")]] <- # some other generating function
}
Gregor Thomas
  • 104,719
  • 16
  • 140
  • 257
DaveArmstrong
  • 6,161
  • 1
  • 5
  • 14