Behzod A
Behzod A

Reputation: 313

R for loop dataframe variable names

I am new to R and loops. I have a data frame (xyz). I am running a loop and want to save a new new data frames under different names.

states <- c("AL",   "AK")
keywords <- c("snow", "rain")
filepath <- file.path("C:/data/")

for(state_var in states) 
for(key_var in keywords) 
{
save(xyz, file = (file.path(filepath, paste0(state_var, sep = "_", key_var,".RData"))))
}

Everything is working perfectly and new data frame is saved under different names. But when I load saved data frames all data frames have exactly same name xyz.

How it is possible to save under different df name. Thanks a lot.

Upvotes: 1

Views: 62

Answers (2)

Behzod A
Behzod A

Reputation: 313

Thank you for everyone. I was able to solve this question. It turns that assign does not work inside the function. And we have to use the list. Here is the solution:

states <- c("AL",   "AK")
keywords <- c("snow", "rain")
filepath <- file.path("C:/data/")

for(state_var in states) 
for(key_var in keywords) 
{
assign(paste(state_var, key_var, sep="_"), xyz)
save(list = paste(state_var, key_var, sep="_"), file = (file.path(filepath, paste0(state_var, sep = "_", key_var,".RData"))))
}

Upvotes: 1

Jan
Jan

Reputation: 5274

Try this:

states <- c("AL",   "AK")
keywords <- c("snow", "rain")

for(state_var in states) 
  for(key_var in keywords) 
  {
    objname <- paste(state_var, key_var, sep="_")
    assign(objname, xyz)
    save(list = objname, file = (file.path(filepath, paste0(state_var, sep = "_", key_var,".RData"))))
    rm(objname) # make sure you get rid of this again
  }

Save stores the saved object as is. That includes the name. With assign you create a new variable with the name you want.

Upvotes: 2

Related Questions