[英]Use of lapply with custom functions of several arguments
我在將lapply與我創建的自定義函數一起使用時遇到了麻煩,但這是一個相當具體的函數,我一直無法找到適合我的答案。
該函數很長,可以完成很多事情,但是我認為我已經將其縮小為一個可重現的示例,給出了我遇到的錯誤。
問題是,我有一個包含兩種不同類型文件的文件夾,我想將其作為列表元素加載到R中。 它們或多或少具有相同的信息,但是它們具有不同的布局,不同的文件擴展名,幾乎所有內容都不同,因此每種類型的導入過程都不同。
該函數如下所示:
f <- function(a_file, b_file, type){
if (type == "a"){act <- read.table(a_file, skip = 19, header = TRUE, sep = "", dec = ".")}
if (type == "b"){act <- read.table(b_file, header=FALSE, sep="\t", dec=".")}
return(act)}
然后,使用要調用的兩種文件類型的名稱創建矢量,如下所示:
a_files <- dir(pattern=".deg")
b_files <- dir(pattern=".act")
最后嘗試應用如下功能:
act_list <- lapply(a_files, f, b_files, type = "b")
如果type = "a"
,但是對於type = "b"
失敗,給出錯誤:
Error in file(file, "rt") : invalid 'description' argument
我敢肯定,這與我僅將該函數應用於“ a_files”向量而不是“ b_files”這個事實有關,但是我盡我所能設法解決此問題。 ..
有一種更簡單的方法可以解決您的問題。
首先,將函數定義為文件名僅具有一個參數。
然后在其中確定文件是哪種類型,並進行正確的讀取類型。
readFiles = function(file){
if(grepl(file,pattern = "\\.deg")){
act <- read.table(a_file, skip = 19, header = TRUE, sep = "", dec = ".")
}
if(grepl(file,pattern = "\\.act")){
act <- read.table(b_file, header=FALSE, sep="\t", dec=".")
}
return(act)
}
最后,您只需要在文件向量上調用lapply
:
filesVector = dir(pattern = "(\\.act|\\.deg)")
result = lapply(filesVector, readFiles)
filesVector
將返回所有包含“ .act”或“ .deg”的文件。
注意:您的模式不正確,因為它將返回包含任何字符后跟“ act”或“ deg”的文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.