Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

save an R dataframe with the name specified by a string

Tags:

r

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.

like image 730
Curious2learn Avatar asked Jun 11 '11 19:06

Curious2learn


People also ask

How do I convert a string to a Dataframe in R?

Use str_replace() method from stringr package to replace part of a column string with another string in R DataFrame.

How do you give a Dataframe a title in R?

Method 1: Using colnames() function colnames() function in R is used to set headers or names to columns of a dataframe or matrix. Syntax: colnames(dataframe) <- c(“col_name-1”, “col_name-2”, “col_name-3”, “col_name-4”,…..)

How do I save a Dataframe in R?

To save data as an RData object, use the save function. To save data as a RDS object, use the saveRDS function. In each case, the first argument should be the name of the R object you wish to save. You should then include a file argument that has the file name or file path you want to save the data set to.


2 Answers

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') 
like image 116
Sacha Epskamp Avatar answered Oct 24 '22 09:10

Sacha Epskamp


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')
like image 28
Gavin Simpson Avatar answered Oct 24 '22 09:10

Gavin Simpson