Aite97
Aite97

Reputation: 165

How to create variables with different names in for loop iterations in R?

I am trying to create a loop in R which for each iteration stores the calculations in the loop in a variable with a unique name. A very simple example would be if I have two variables, say boy heights and girl heights, and wanted to store the average boy and girl heights in the variables avg.boyheight and avg.girlheight respectively. I tried to use paste("avg,"i", ".") on the lhs and storing the mean(x.height) like this:

df <- as.data.frame(cbind(bh = c(1,2,3,4,5), gh = c(4,2,5,1,4)))
for(i in 1:2) {
 paste("avg",colname(df)[i],".") <- mean(df[,i])
}

I get an error as the paste() thing apparently is not applicaple in object name creation.

How can I generate the distinct variable names during the loop?

Of course what I'm really doing inside my loop will be more complicated, however I need to be able to store the different iteration in their own variable name.

Upvotes: 0

Views: 293

Answers (1)

dww
dww

Reputation: 31452

You can save the results in a list using sapply. This would typically make more sense than saving each one as a separate object in the global environment.

avg = sapply(df, mean, simplify = FALSE, USE.NAMES = TRUE)

The you can access each one like this

avg$bh
# [1] 3
avg$gh
# [1] 3.2 

Upvotes: 1

Related Questions