【问题标题】:Re-writing a for-loop as a lapply function in R在 R 中将 for 循环重写为 lapply 函数
【发布时间】: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


    【解决方案1】:

    您可以在这里充分利用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") 
    

    【讨论】:

    • 这简直太美了
    • @RichScriven 非常感谢。这删除了很多代码:)
    猜你喜欢
    • 2021-02-16
    • 2020-04-26
    • 2015-10-12
    • 2017-07-12
    • 1970-01-01
    • 2017-04-20
    相关资源
    最近更新 更多