我想知道为什么purrr中的cant map函数无法解决此查询
tapply(mtcars$mpg, mtcars$cyl, mean)
# 4 6 8
#26.66364 19.74286 15.10000
与
mtcars %>% split(.$cyl) %>% map(~mean(mpg))
#$4
[1] NA
#$6
[1] NA
#$8
[1] NA
#Warning messages:
1: In mean.default(mpg) : argument is not numeric or logical: returning NA
2: In mean.default(mpg) : argument is not numeric or logical: returning NA
3: In mean.default(mpg) : argument is not numeric or logical: returning NA
答案 0 :(得分:1)
我们需要提取特定列
library(purrr)
mtcars %>%
split(.$cyl) %>%
map(~mean(.$mpg))
如果我们需要获得vector
mtcars %>%
split(.$cyl) %>%
map_dbl(~mean(.$mpg))
# 4 6 8
#26.66364 19.74286 15.10000