【发布时间】:2018-04-28 21:40:09
【问题描述】:
我有几个包含一系列数字的文件。我想找出所有文件中的共同数字是什么。例如
a.txt
1
2
3
4
b.txt
2
4
9
c.txt
2
3
4
8
10
输出:2、4
我使用 for 循环编写的代码给了我正确的结果。
fileList = c("a.txt", "b.txt", "c.txt")
for(i in 1:length(fileList)){
tempDF = read.table(fileList[1], header = T, stringsAsFactors = F)
if(i == 1){
commons = tempDF$x
}else{
commons = intersect(commons, tempDF$x)
}
}
print(commons)
但是我在使用 lapply 函数重写它时遇到了一些麻烦。 lapply 如何在不替换的情况下保持“公共”变量的值?
lapply(fileList, function(x) getCommons(x))
getCommons <- function(file){
fileData = read.table(file, header = T, stringAsFactor = F)
commons = intersect(commons, fileData)
}
【问题讨论】:
标签: r performance for-loop lapply