函数适用于列表的一个元素,不适用于完整列表,R



我正在尝试制作一个函数来向数据帧添加标记。数据框的名称包含了我需要的信息(日期、选择、治疗等(。所以我做了一个函数来提取我需要的数据。我有一个包含所有数据帧的大列表,当我将函数应用于该列表时,它确实为标记创建了新列,但值是NA-s。每个数据帧都有相同的名称结构,如果我从列表中提取一个数据帧并运行函数,它就会工作。你能帮我找出为什么当我把它应用到列表中时它不起作用吗?

这是我的功能:

library(stringr)
tagging <- function(H){
namey<-deparse(substitute(H)) #get the name of the data frame 
namey<- str_sub(namey,1, -5) #drop the .csv 
H$date<-substring(namey,1, 6) # get the first 6 characters containing the date 
H$selection<- word(namey, -1) #get the last word 
H$treatment<- word(namey, -2) # get the second last word
H$REP<- word(namey, -3) # get the third last word 
return(H)
}

我像这个一样应用它

ListofData.tagged<-lapply(ListofData, tagging)

数据帧的名称如下:

180503 xyz1-6 R4_A6_xyz 5 yes.csv

以这种方式导入,以便保留您的名称:

library(tidyverse)
ListofData <- map(set_names(temp), read_csv)

然后我们修改您的函数,将名称添加为第二个参数,该参数将通过imap使用,因此我们也去掉了第一行:

tagging <- function(H, namey){
namey<- str_sub(namey,1, -5) #drop the .csv 
H$date<-substring(namey,1, 6) # get the first 6 characters containing the date 
H$selection<- word(namey, -1) #get the last word 
H$treatment<- word(namey, -2) # get the second last word
H$REP<- word(namey, -3) # get the third last word 
return(H)
}

然后imap将数据传递给H参数,并将元素名称传递给namey参数。

ListofData.tagged <- imap(ListofData, tagging)

基本R翻译

ListofData <- lapply(setNames(temp,temp), read.csv)
ListofData.tagged <- Map(tagging, ListofData, names(ListofData))

或者,如果您不关心命名ListofData的元素,您可以直接命名Map(tagging, ListofData, temp)(仍然保留tagging的新定义(。

最新更新