简体   繁体   中英

Save a data frame to a file addressing by name

I have a data frame and a text variable containing the name of this data frame:

adsl = data.frame(a=2, b=7, w=17)
ds_name = "adsl" 

I want to save my data frame from the workspace to the file named "dest_file". The code should be wrapped into a function get_r() with the data frame name as an argument:

get_r(ds_name="adsl")

So I need to avoid using the explicit name "adsl" inside the code.

The following works almost correctly but the resulting data frame is called "temp_dataset", not "adsl":

get_r = function(ds_name){
    temp_dataset = eval(parse(text=ds_name))
    save(temp_dataset, file = "dest_file")
}

Here is another option which works wrong (the text string is being saved, not the data frame):

get_r = function(ds_name){
    save(ds_name, file = "dest_file")
}

What should I do to make R just execute

save(adsl, file="dest_file") 

inside the function? Thank you for any help.

Try

save(list = ds_name, file = "dest_file")

The list argument in save() allows you to pass the name of the data as a character string. See help(save) for more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM