1

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.

2
  • How do you load the saved dataframes back? Commented May 24, 2020 at 11:58
  • I was just using load(file.path(filepath, "AL_snow.RData")) Commented May 24, 2020 at 15:42

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi @Jan I am getting following error: object ‘assign("objname", xyz)’ not found
You're right. Wow! Fascinating!! The object existed but somehow save wasn't able to work with it. I fixed it. Tested it to the end this time.
1

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"))))
}

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.