首页 > 解决方案 > 使用 lapply 创建要在循环中使用的 R 函数

问题描述

我有数千个 txt 文件(1.txt;2.txt;3.txt...)用作输入(预测),还有另一个文件称为“标签”。我需要运行几个命令来创建它们各自的输出(AUC 值)。我正在使用上一篇文章中的建议(循环遍历 R 目录中的所有文件,应用多个命令)。

但是我在创建要包含在此循环中的函数时遇到了麻烦。

我的原始代码(1个文件predictions):

library(ROCR)
labels <- read.table(file="/data/labels/labels", header=F, sep="\t")
predictions <- read.table(file="/data/input/3.txt", header=F)
pred <- prediction(predictions, labels)
perf <- performance(pred,"tpr","fpr")
auc <- attr(performance(pred ,"auc"), "y.values")
auc
write.table(auc, "/data/out/AUC3.txt",sep="\t")

到目前为止我的代码(不工作):

library(ROCR)
labels <- read.table(file="/data/labels/labels", header=F, sep="\t")

files <- list.files(path="/data/input/", pattern="*.txt", full.names=TRUE, recursive=FALSE)

auc <- function(r) {
    pred <- prediction(files, labels)
    perf <- performance(pred,"tpr","fpr")
    auc <- attr(performance(pred ,"auc"), "y.values")
}

lapply(files, function(x) {
    t <- read.table(x, header=F) # load file
    out <- auc(t)
    write.table(out, "/data/out/", sep="\t")
})

错误信息:

Error in prediction(files, labels) :
Number of predictions in each run must be equal to the number of labels for each run.
Calls: lapply -> FUN -> auc -> prediction
Execution halted

标签: rloopslapply

解决方案


问题是这种说法files$V1files由创建list.files并且该函数返回一个原子向量(请参阅 参考资料?list.files)。您不能$与原子向量一起使用。files[###]您必须使用具有###正确索引的数字索引来寻址元素。


推荐阅读