首页 > 解决方案 > 将文件读入 R,然后对它们应用相同的函数并返回结果文件

问题描述

我有 100 多个具有相同列的文件。我使用以下代码将它们读入 R:

# packages
require(data.table)
# set wd
setwd("PathToYourFolder")
# import files
files = list.files(pattern="*.txt.results")

我想将以下功能应用于所有这些文件:

fdr <- p.adjust (file$col4, method = "fdr", n = length(file$col4)) 

我尝试了以下方法:

lapply(files, p.adjust (files$col4, method = "fdr", n = length (files$col4)))

你能告诉我怎么做吗?

标签: rfunctioniterationlapply

解决方案


好吧,你很接近。


your.p.values <- lapply(files, function(file) {

    dat <- read.csv( file )
    
    p.adjust (dat$col4, method = "fdr", n = length (dat$col4)))

})

## add the filenames to them to keep better order of things:
names(your.p.values) <- files

包中有一个函数purrr可以为您将文件的名称添加到列表中,为您节省一步并稍微简化代码,但上述解决方案应该可以解决这个问题。


推荐阅读