abruh
abruh

Reputation: 93

Looping through files in R and applying a function

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?

Upvotes: 1

Views: 363

Answers (1)

Thierry
Thierry

Reputation: 18487

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)

Upvotes: 2

Related Questions