Enjoy R: how to automatically give readable names to variables in a loop

For making the same operations on each element of a collection — e.g. vector, matrix, list —, we generally use loops. Sometimes, we want to save the results of each iteration in variables which are related only to the current iteration. To do that properly, we should give each variable a name that simoultaneously refers to both the operation and the iteration.

Let’s suppose we want to compute mean and standard deviation of the following three populations:

rm(list = ls())
NPOP <- 10000
distributions <- data.frame(NORM = rnorm(NPOP), 
                            LOGNORM = rlnorm(NPOP),
                            CHISQ = rchisq(NPOP, 3))

An easy way to save each result in a different variable, is to exploit the assign function, whose first two arguments are the variable (a string) and the value, respectively.

for(i in seq_along(distributions)) {

  # create the variable name for the mean of distribution i
  mean_variable <- paste0('mean_', names(distributions)[i])
  
  # assign the corresponding value to the label
  assign(mean_variable, mean(distributions[, i]))  

  # create the variable name for the s.d. of distribution i
  sd_variable <- paste0('sd_', names(distributions)[i])
  
  # assign the corresponding value to the label
  assign(sd_variable, sd(distributions[, i]))  
}

rm(list = c('mean_variable', 'sd_variable', 
            'NPOP', 'distributions', 'i')) 
ls() # it worked !

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: