r - 使用 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
解决方案
问题是这种说法files$V1
。files
由创建list.files
并且该函数返回一个原子向量(请参阅 参考资料?list.files
)。您不能$
与原子向量一起使用。files[###]
您必须使用具有###
正确索引的数字索引来寻址元素。
推荐阅读
- ruby-on-rails - Rails 5 InvalidAuthenticityToken Coffeescript
- php - 将变量传递给 Blade 导致 increment() 将 DB 字段增加两次
- python - 如何从给定的二叉搜索树的后序遍历中找到前序遍历
- pandas - 向数据框添加列
- eclipse - 为什么 Eclipse 以红色突出显示我的代码以及如何将其关闭?
- java - 通过搜索类变量删除 ArrayList 中的元素
- haskell - 通过归纳证明指数运行时间
- time - CPI和命令执行时间计算问题
- python - 记录警告后卡住,如何强制继续?
- python - SQLAlchemy:如何正确执行 time_created 和 time_modified