kingmidaz
kingmidaz

Reputation: 63

rename data frame to rotating variable

My question is similar to the one here (Rename data frame), but I am trying to rename it based on a rotating variable name.

df2<-data.frame(a=seq(1:5),b=c(1:10), c=c(11:20))
df2$a = c('alpha', 'alpha','alpha', 'beta', 'beta', 'gamma', 'beta','alpha',    'alpha','alpha')

variables<- c('alpha', 'beta', 'gamma')

for (var in variables) {
alpha<- df2
beta<- df2
gamma<- df2
}

Instead of having the three lines to create a copy of df2 named alpha, beta, gamma I want to have one line to create the copy of df2, so have

var <- df2

inside the loop, and as var rotates with the loop, so after its three runs through the loop I would have alpha,beta,gamma as above as it goes through the loop. My real purpose is I am using the same data frame and then doing a number of calculations on it, and then want to name the resulting data frame after the variable that is currently being used in the loop.

I know that in bash I would do data_${var} and it would result with data_alpha, data_beta, data_gamma, but what about in R?

Any one know how to do this?

Thanks!

Upvotes: 0

Views: 190

Answers (2)

Greg Snow
Greg Snow

Reputation: 49650

This is FAQ 7.21. The most important part of that answer is where it says not to do this.

What would be better is to use a list and assign your copies into the list:

variables<- c('alpha', 'beta', 'gamma')

mydfs <- list()

for (var in variables) {
  mydfs[[var]] <- df2
}

Or for just the above:

mydfs <- rep( list(df2), length(variables) )
names(mydfs) <- variables

Then additional processing can be done using lapply, sapply or similar functions.

Upvotes: 1

Neal Fultz
Neal Fultz

Reputation: 9687

You could do something like assign(var, df2).

Upvotes: 0

Related Questions