0

I want to save several objects in a loop in separate files, but I have problems getting it right. Below is the code (a highly simplified example of the thing I am doing). I want the objects a2014 and b2014 to be saved to a2014.Rdata and b2014.Rdata. The code clearly does not work as the object parametername is saved and not the objects a2014 and b2014.

for (i in c("a","b")) {
   data <- c(1,2)
   parametername <- paste0(i,"2014")
   assign(parametername, data)
   save(parametername, file = paste0(i, "2014.Rdata")) # This is clearly not working
}

Any help is appreciated.

Cheers

Renger

1 Answer 1

1

You can pass the object name in list.

for (i in c("a","b")) {
  data <- c(1,2)
  parametername <- paste0(i,"2014")
  assign(parametername, data)
  save(list = parametername, file = paste0(i, "2014.Rdata")) 
}
Sign up to request clarification or add additional context in comments.

7 Comments

If I run your first example, this is not working. I want the data to be saved as a2014 and b2014. In your example it is saved as data1.
Yes, the values are saved in data1 but when I run the first part of my code there are objects called a2014 and b2014 in my global environment. As well as a2014.Rdata and b2014.Rdata in my working directory.
Sorry, missed that one. Thanks. However, I really would like to have them also saved as a2014 and b2014 automatically.
@arnyeinstein They are already saved as a2014 and b2014 automatically. After you run the above code type a2014 in the console to see it. That is what first part of my answer is doing.
Yes, but if you restart or remove a2014 and b2014 and load a2014.Rdata, there is no a2014. Only a data1. I want a2014 to be saved as a2014 in the loop.
|

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.