【问题标题】:Looping through files in R and applying a function在 R 中循环文件并应用函数
【发布时间】:2015-10-25 02:58:13
【问题描述】:

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

这是应用于单个文件的函数

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

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

然后我可以吐出一个值

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

我尝试格式化某人在此板上制作的另一个文件循环。该链接在这里:

Looping through files in 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)
}

我做错了什么/有什么更好的方法?

【问题讨论】:

    标签: r csv


    【解决方案1】:

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

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

    然后将该函数应用于文件名向量

    the.files <- list.files()
    index <- sapply(the.files, stratindex)
    output <- data.frame(File = the.files, StratIndex = index)
    write.csv(output)
    

    【讨论】:

    • 我在该代码中的什么位置告诉它从哪个文件夹中获取文件列表?
    • 我明白了,谢谢。对于其他看到此内容的人-您可以使用“choose.files()”代替“list.files()”来手动选择它们。
    猜你喜欢
    • 2019-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-21
    • 1970-01-01
    相关资源
    最近更新 更多