0

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.

1
  • 1
    are you sure you need that? Resorting to dynamically generated variable names is usually an indication that something should be done differently. Why can't you just do: this_mean = mean(df[,i]) and then work with this_mean inside the block? Commented Mar 21, 2021 at 15:45

1 Answer 1

1

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 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.