Specify path in write.csv function

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)

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 = ''))

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 = ".\\")

Tags:

R