【发布时间】:2018-11-16 18:06:31
【问题描述】:
我正在尝试创建一个向数据框添加标签的函数。 数据框的名称包含我需要的信息(日期、选择、治疗等...)。所以我做了一个函数来提取我需要的信息。我有一个包含所有数据框的大列表,当我将函数应用于列表时,它确实为标签创建了新列,但值是 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
【问题讨论】:
-
你能证明
ListofData包含什么的最小例子吗? -
看起来是文件名而不是对象名。我认为您需要遍历
ListofData的名称? -
试试
map(names(ListofDatalst), ~ str_sub(.x, 1, -5)) -
问题是
lapply问题:它将X[[1]],然后X[[2]]等传递给函数。将cat("namey:", namey, "\n")放在deparse/substitute之后,看看函数中的df 名称是什么。 -
Anders Ellern Bilgrau:ListofData 包含 300 个数据帧。每个数据框都具有相同的结构、相同的变量和相同的名称“结构”。 akrun:文件名就是对象名,因为我导入的.csv文件如下: temp = list.files(pattern="*.csv") ListofData = lapply(temp, read.csv)跨度>
标签: r list function user-defined-functions lapply