Home > Back-end >  How to write multiple csv files to specific directory in R within a by (group) function?
How to write multiple csv files to specific directory in R within a by (group) function?

Time:03-13

I am attempting to export multiple files by group of my data frame. The following code works great, but the files are exported into the working directory. I need to export these to a different directory: different_folder

by(df, df$Subject, FUN=function(i) write.csv(i, paste0(i$Subject[1], ".csv"), quote = F))

Thanks.

CodePudding user response:

Here is a way. It uses file.path to form a file name in a OS independent way. From the documentation, my emphasis.

file.path {base}
Construct Path to File
Description
Construct the path to a file from components in a platform-independent way.

Note also that I have added a verbose argument, defaulting to FALSE. Remove it from the call (verbose = TRUE, near the end) if the screen is being cluttered by unwanted feedback.

df <- iris
names(df)[5] <- "Subject"

different_folder <- "~/Temp"
by(df, df$Subject, FUN = function(i, verbose = FALSE) {
  outfile <- file.path(different_folder, paste0(i[1, "Subject"], ".csv"))
  if(verbose) cat("output file:", outfile, "\n")
  write.csv(i, outfile, quote = FALSE, row.names = FALSE)
}, verbose = TRUE)
#> output file: ~/Temp/setosa.csv 
#> output file: ~/Temp/versicolor.csv 
#> output file: ~/Temp/virginica.csv
#> df$Subject: setosa
#> NULL
#> ------------------------------------------------------------ 
#> df$Subject: versicolor
#> NULL
#> ------------------------------------------------------------ 
#> df$Subject: virginica
#> NULL

Created on 2022-03-12 by the reprex package (v2.0.1)

CodePudding user response:

You need to also add the directory to the path you are giving:

df <- data.table(1:20, 
             1:20, 
             Subject= rep(c("A", "B"), each= 10),
             directory= rep(c("test1", "test2"), each= 10))
dir.create("test1")
dir.create("test2")
by(df, df$Subject, FUN=function(i) write.csv(i, paste0(i$directory[1], "/", i$Subject[1], ".csv"), quote = F))

Note that the directory will be relative to your working directory. Providing full path can be safer. Make sure that the directory exists before running your code

  •  Tags:  
  • r
  • Related