Andy Clifton
Andy Clifton

Reputation: 5056

Using variable names in arrays to identify and save data to files

I have a series of data.frames in R that I would like to save as text files so I can share them with others.

Let's call the data.frames a, b, c, etc. I can write a simple loop to save these:

for (mydata in c("a",
                 "b",
                 "c")){
  write.csv(x = get(mydata),
            file = file.path("datadump",paste0(mydata,".csv")))  
}

However, some of the other data I want to save are lists; l1, l3, l4, etc. I want to use the same method to save the data, but I can't figure out how to just save one element. For example,

for (mydata in c("a",
                 "b",
                 "l1$x")){
  write.csv(x = get(mydata),
            file = file.path("datadump",paste0(mydata,".csv")))  
}

returns an error: Error in get(mydata) : object 'l1$x' not found. I've also tried referring to the lists as l1[[x]], and that doesn't work either. Any suggestions?

Upvotes: 1

Views: 52

Answers (1)

Julien Navarre
Julien Navarre

Reputation: 7830

Try with eval(parse(text = "l1$x"))

(Thank you)

Upvotes: 2

Related Questions