简体   繁体   中英

Write data.frame to CSV file and use theire variable name as file name

I have 3 dataframes, df1,df2,df3. I need to convert these df to csv files. So, i am using write.csv as below, with the help of function.

    hiveq <- function(f_name){
        f_name
        write.csv(f_name,file=paste(f_name,".csv",sep=""),row.names = FALSE, col.names = FALSE)}
hiveq("df1")
hiveq("df2")
hiveq("df3")

When i opened csv sheet, it shows only df1, not the content of df1. How can i say to R that, it should see as Df and not as string. I tried using as.name, gsub, as.formula to remove quotes around the f_name variable, but not working. can some one help me in this?

A convenient way to do this is with "non-standard evaluation". Here is how this would work in your case:

hiveq <- function(df) {
  write.csv(df, file = paste(deparse(substitute(df)),".csv",sep=""), row.names = FALSE, col.names = FALSE)
}
hiveq(df1)
hiveq(df2)
hiveq(df3)

What happens here is that the expression deparse(substitute(df)) returns a character string containing the name of the R object passed to df . So when you call:

hiveq(df1)

that evaluates to "df1" and the function writes the data frame to a file called "df1.csv".

The problem is that the x argument of write.csv expects a dataframe while the file argument has to be a character string. So you have two options.

1st option : Use get() to find the dataframe from its name:

hiveq <- function(d, env = parent.frame()) {
    write.csv(get(d, env = env),
              file = paste0(d,".csv"),
              row.names = FALSE)
}
hiveq("df1")

You need to set the env argument here to parent.frame() , otherwise get() will have to resolve ambiguity about where to look for the object.

2nd option : Supply the dataframe and extract its name using non-standard evaluation:

hiveq <- function(d) {
    write.csv(d,
              file = paste0(deparse(substitute(d)), ".csv"),
              row.names = FALSE)
}
hiveq(df1)

In sum, get() would give you the object under that name, while the deparse(subtitute()) combination gets the name of the object as a string.

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