Naus
Naus

Reputation: 99

Looping in R like in Stata

I'm sure that this is very simple but I cannot find a way to translate this simple loop in Stata to R.

In the loop is the following

forvalues i=1/8{
  gen foo`i'=foo`i'.bar.1+foo`i'.bar.2
}

where the foo's are numeric vector variables. So, the loop is using gen to create eight new variables that are each a sum of two different sets of variables. I'm not sure how to translate that loop into R

Upvotes: 1

Views: 2351

Answers (1)

farnsy
farnsy

Reputation: 2470

I'm not a stata person but it looks like you are creating a set of variables distinguished by numbers in their name by adding two other sets of variables (created elsewhere) that are named the same way. This is not typically the way we do things in R because it's too easy to create a list of variables and then refer to each variable by its index. There are tons of options, but one R approach would be something like

foo <- list()
for (i in 1:8){
   foo[[i]] <- foo.bar.1[[i]] + foo.bar.2[[i]]
}

R actually has innumerable types of data containers, so there could be many others that are better for your application.

But anyway if you really want to include the number in the variable name, you can use the assign() and get() functions. Something like

for (i in 1:8){
   assign(paste("foo",i,sep=''),get(paste("foo",i,".bar.1",sep=''))+get(paste("foo",i,".bar.2",sep='')))
}

Upvotes: 6

Related Questions