r - 在 R 中将 for 循环重写为 lapply 函数
问题描述
我有几个包含一系列数字的文件。我想找出所有文件中的共同数字是什么。例如
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)
}
解决方案
你可以好好利用Reduce
这里。而且由于在每个文件中都有一个不一定是数据框的列(没有列名),我们可以read.table
用scan
. 这将生成一个包含三个数字向量的列表,从而更容易、更快地找到交点。
Reduce(intersect, lapply(files, scan, quiet = TRUE))
# [1] 2 4
数据创建:
write(1:4, file = "a.txt", sep = "\n")
write(c(1, 2, 4, 9), file = "b.txt", sep = "\n")
write(c(2, 3, 4, 8, 10), file = "c.txt", sep = "\n")
files <- c("a.txt", "b.txt", "c.txt")
推荐阅读
- html - 如何让 CodeMirror 适合垂直弹性盒的剩余空间
- ios - 填充矩形而不干扰 HStack 的几何形状
- solr - SOLR:如何忽略 MinFieldValueUpdateProcessorFactory 处理器中的 0(零)值?
- python - 从列表中创建数据框中的列(列数更改)
- node.js - 使用 JavaScript 框架和 Node.js 进行身份验证
- c# - 在 HoloLens 2 上访问 MediaFrameSourceGroup 参数的问题
- angular - 检查后表达式已更改。以前的值:''。当前值:“测试”
- javascript - currentFocusedField 已弃用,将在未来版本中使用 TextInput 道具“secureTextEntry”时删除
- reactjs - 如何将 JWT 令牌存储在 cookie React fetch 中
- android - 在 Intune 门户中打开应用程序的深度链接或动态链接