Curious2learn
Curious2learn

Reputation: 33648

save an R dataframe with the name specified by a string

On this awesome forum I saw a post which shows how to convert a string to a variable and assign a data frame to that variable. For example:

x = "thisisthestring"

# df is a data frame
assign(x, df) # This will assign data frame df to variable thisisthestring

What I want to do is save this data frame with the name thisisthestring. However, if I try

assign(x, df)
save(x, file='somefilename.rda') 

the file just contains a string "thisisthestring" and not the data frame df.

I also tried

save(assign(x, df), file = 'somefile.rda'))

That does not work either. Any suggestions how I can save the data frame to a file, where the name of the data frame is specified by the string.

Upvotes: 10

Views: 5018

Answers (2)

Gavin Simpson
Gavin Simpson

Reputation: 174948

You want to pass x as the argument list to the save() function, not as part of argument ... (the first argument of save()). This should work:

save(list = x, file='somefilename.rda')

Upvotes: 6

Sacha Epskamp
Sacha Epskamp

Reputation: 47642

Add x to the listargument from save(). From the help file:

list A character vector containing the names of objects to be saved.

save(list=x, file='somefilename.rda') 

Upvotes: 16

Related Questions