Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dataframe

r

csv

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?

like image 965
subro Avatar asked Apr 11 '16 12:04

subro


People also ask

How do you name a CSV file?

Rules for CSV file namingThe file name must begin with a table or group reference, followed by a start time, and end in . CSV. The start time in the file name must be at or before the first time stamp in the file. The end time is optional and can be at or after the last time stamp in the file.

Which functions can be used to write data into CSV files?

The csv. writer() function returns a writer object that converts the user's data into a delimited string. This string can later be used to write into CSV files using the writerow() function.


2 Answers

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".

like image 123
zakrapovic Avatar answered Oct 17 '22 12:10

zakrapovic


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.

like image 2
niczky12 Avatar answered Oct 17 '22 12:10

niczky12