Send output file from for loop to a new directory in R

directory, for-loop, r

Solution

So assuming that the folders don't already exist, and you want to create them and then put output.csv in each, the following should work:

p <- "~/Desktop/MyFolder"
setwd(p)

files <- list.files(path=dir, pattern="csv$", full.names=FALSE, recursive=FALSE)

for(i in 1:length(files)){

  f <- lapply(files[i], read.csv, header=TRUE, stringsAsFactors=FALSE)
  #why not:
  #f <- read.csv(files[i],header=TRUE, stringsAsFactors=FALSE)
  cat2 <- f[f$mod ==2, c(1,6)] 
  dir.create(paste0("folder",i), showWarnings = FALSE) #stops warnings if folder already exists
  write.csv(cat2, file.path(paste0("folder",i), "output.csv"), row.names=FALSE)
}

Your `lapply()` statement looks unnecessary to me, but maybe there's something that I'm missing

Problem

I have used a for loop to load some files, perform some tasks and write the results to a new csv file. The directory where the input files are stored was set before running the loop, but rather than saving the output csv file to the same directory, I would like to send it to a new directory within the loop. Here is a very simple for loop example: ``` p <- "~/Desktop/MyFolder" setwd(p) files <- list.files(path=dir, pattern="csv$", full.names=FALSE, recursive=FALSE) for(i in 1:length(files)){ f <- lapply(files[i], read.csv, header=TRUE, stringsAsFactors=FALSE) cat2 <- f[f$mod ==2, c(1,6)] filename <- files[1] tn <- strsplit(filename,"_")[[1]][1] fn <- paste(tn, "_trimmed.csv", sep="") write.csv(cat2, file=fn, row.names=FALSE) } ``` I am quite new to R and have not been able to find out how to do this. Any help would be appreciated.

Original source