1

I'm not a very experienced R user. I need to loop through a folder of csv files and apply a function to each one. Then I would like to take the value I get for each one and have R dump them into a new column called "stratindex", which will be in one new csv file.

Here's the function applied to a single file

ctd=read.csv(file.choose(), header=T)

stratindex=function(x){
x=ctd$Density..sigma.t..kg.m.3..
(x[30]-x[1])/29
}

Then I can spit out one value with

stratindex(Density..sigma.t..kg.m.3..)

I tried formatting another file loop someone made on this board. That link is here:

Looping through files in R

Here's my go at putting it together

out.file <- 'strat.csv'
for (i in list.files()) {
tmp.file <- read.table(i, header=TRUE)  
tmp.strat <- function(x)
x=tmp.file(Density..sigma.t..kg.m.3..)
(x[30]-x[1])/29
write(paste0(i, "," tmp.strat), out.file, append=TRUE)
}

What have I done wrong/what is a better approach?

Community
  • 1
  • 1
abruh
  • 81
  • 6

1 Answers1

2

It's easier if you read the file in the function

stratindex <- function(file){
    ctd <- read.csv(file)
    x <- ctd$Density..sigma.t..kg.m.3..
    (x[30] - x[1]) / 29
}

Then apply the function to a vector of filenames

the.files <- list.files()
index <- sapply(the.files, stratindex)
output <- data.frame(File = the.files, StratIndex = index)
write.csv(output)
Thierry
  • 18,049
  • 5
  • 48
  • 66
  • Where in that code do I tell it what folder to take the file list from? – abruh Oct 24 '15 at 19:15
  • 1
    I got it, thanks. For anyone else that looks at this- you can use "choose.files()" in place of "list.files()" to manually choose them. – abruh Oct 24 '15 at 20:19