本文介绍了无法识别地图函数内的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个嵌套的数据框,我想获取子数据框中每一列不为 NA 的行数,如下(简化版):
I have a nested dataframe and I would like to get the numbers of rows which is not NA for each column in the child dataframe as follows (simplified version):
df <- list(
tibble(a=c(1, 2, NA_real_, 4, 5), b=c(2, NA_real_, 5, NA_real_, 3)),
tibble(a=c(NA_real_, 2, 3, NA_real_, 5), b=c(NA_real_, NA_real_, NA_real_, 1, 3))
) %>%
tibble(x=1:2, y=.)
res <- df %>%
mutate(z=map(y, function(dat){
c(a="a", b="b") %>% map_int(function(col){
dat %>% filter(!is.na(!!sym(col))) %>% nrow()
}) %>% enframe()
}))
当我运行代码时,我收到一条错误消息:错误:只有字符串可以转换为符号
.函数内部的 col
好像无法识别.
为什么会出现这种行为?
When I run the code, I get an error that says: Error: Only strings can be converted to symbols
. It seems that col
inside the function is not recognized.
Why does this behavior occur?
推荐答案
如果你的数据叫做 df
,你可以这样做:
If your data is called df
, you could do :
library(dplyr)
library(purrr)
df1 <- df %>% mutate(res = map(y, ~.x %>% summarise_all(~sum(!is.na(.)))))
df1$res
#[[1]]
# A tibble: 1 x 2
# a b
# <int> <int>
#1 4 3
#[[2]]
# A tibble: 1 x 2
# a b
# <int> <int>
#1 3 2
或者使用基础 R :
sapply(df$y, function(x) colSums(!is.na(x)))
这篇关于无法识别地图函数内的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!