# 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

- Posted in: R ♦ rstats ♦ statistical software
- Tagged: assignment, loops, r, rstats, statistical software

## Recent Comments