簡體   English   中英

在R中將for循環重寫為lapply函數

[英]Re-writing a for-loop as a lapply function in R

我有幾個包含一系列數字的文件。 我想找出所有文件中的通用數字。 例如

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(fileList, function(x) getCommons(x))

getCommons <- function(file){

  fileData = read.table(file, header = T, stringAsFactor = F)

  commons = intersect(commons, fileData)

}

您可以在此處充分利用Reduce 而且,由於在每個文件中都有一個不一定是數據幀的列(沒有列名),所以我們可以用scan代替read.table 這將產生三個數值向量的列表,從而使查找交點變得更加容易和快捷。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM