循环浏览R中的文件并应用函数 [英] Looping through files in R and applying a function

查看:136
本文介绍了循环浏览R中的文件并应用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不是一个非常有经验的R用户.我需要遍历一个csv文件文件夹,并对每个文件应用一个函数.然后,我想取每个值,然后让R将它们转储到名为"stratindex"的新列中,该列将在一个新的csv文件中.

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:

在R中循环浏览文件

这是我的努力

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?

推荐答案

在函数中读取文件会更容易

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)

这篇关于循环浏览R中的文件并应用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆