我有这个列表:
list(structure(list(a = 1:10, b = 2:11, c = 3:12), .Names = c("a",
"b", "c"), row.names = c(NA, -10L), class = "data.frame"), structure(list(
a = 1:10, b = 2:11, c = 3:12), .Names = c("a", "b", "c"), row.names = c(NA,
-10L), class = "data.frame"), structure(list(a = 1:10, b = 2:11,
c = 3:12), .Names = c("a", "b", "c"), row.names = c(NA, -10L
), class = "data.frame"))
此功能:
fun1<-function(x){
funs<-c(s=sum,m=mean)
lapply(funs,function(f)f(x,na.rm=TRUE))
}
使用lapply
,结果正常。参见:
list%>%
lapply(function(x){
lapply(x,fun1)
})
但是purrr::map
不起作用:
list%>%
map(.)%>%
map(.,fun1)
怎么了?
答案 0 :(得分:2)
您的地图部分语法错误。您需要使用与lapply相同的代码结构。首先让我们摆脱管道,使代码看起来更相似:
也不要给对象命名与R函数相同的名称。
library(purrr)
lapply_outcome <- lapply(my_list, function(x) {lapply(x, fun1)})
map_outcome <- map(my_list, function(x) {map(x, fun1)})
identical(lapply_outcome, map_outcome)
[1] TRUE
带管道:
my_list %>%
lapply(function(x) lapply(x,fun1))
my_list %>%
map(., function(x) map(x, fun1))
或在地图内部使用公式调用,但就我个人而言,它的可读性较低:
my_list %>%
map(~ map(., fun1))