首页 > 解决方案 > 在 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)

}

标签: rperformancefor-looplapply

解决方案


你可以好好利用Reduce这里。而且由于在每个文件中都有一个不一定是数据框的列(没有列名),我们可以read.tablescan. 这将生成一个包含三个数字向量的列表,从而更容易、更快地找到交点。

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") 

推荐阅读