Specify path in write.csv function

Viewed 40045

I have a simple syntax question: Is there a way to specify the path in which to write a csv file within the .csv function itself?

I always do the following:

setwd("C:/Users/user/Desktop")
write.csv(dt, "my_file.csv", row.names = F)

However, I would like to skip the setwd() line and include it directly in the write.csv() function. I can't find a path setting in the write.csv documentation file. Is it possible to do this exclusively in write.csv without using write.table() or having to download any packages?

I am writing around 300 .csv files in a script that runs auomatically everyday. The loop runs slower when using write.table() than when using write.csv(). The whole reason I want to include the path in the write.csv() function is to see if I can decrease the time it takes to execute any further.

4 Answers

I typically set my "out" path in the beginning and then just use paste() to create the full filename to save to.

path_out = 'C:\\Users\\user\\Desktop\\'
fileName = paste(path_out, 'my_file.csv',sep = '')
write.csv(dt,fileName)

or all within write.csv()

path_out = 'C:\\Users\\user\\Desktop\\'
write.csv(dt,paste(path_out,'my_file.csv',sep = ''))

There is a specialized function for this: file.path:

path <- "C:/Users/user/Desktop"
write.csv(dt, file.path(path, "my_file.csv"), row.names=FALSE)

Quoting from ?file.path, its purpose is:

Construct the path to a file from components in a platform-independent way.

Some of the few things it does automatically (and paste doesn't):

  • Using a platform-specific path separator
  • Adding the path separator between path and filename (if it's not already there)

Another way might be to build a wrapper function around the write.csv function and pass the arguments of the write.csv function in your wrapper function.

write_csv_path <- function(dt,filename,sep,path){ write.csv(dt,paste0(path,filename,sep = sep)) }

Example

write_csv_path(dt = mtcars,filename = "file.csv",sep = "",path = ".\\")

In my case this works fine,

  1. create a folder -> mmult.datas
  2. copy its directory-> C:/Users/seyma/TP/tp.R/tp.R5 - Copy
  3. give a name of your .csv -> df.Bench.csv
  4. do not forget the write your data.frame -> df
  5. write.csv(df, file ="C:/Users/seyma/TP/tp.R/tp.R5 - Copy/mmult.datas/df.Bench.csv")

for more you can check the link

Related