我有一个嵌套的数据框,我想获取子数据框中每一列的行数不是NA,如下所示(简化版本):
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()
}))
运行代码时,出现错误消息:Error: Only strings can be converted to symbols
。似乎函数内的col
无法识别。
为什么会发生这种现象?
答案 0 :(得分:0)
如果您的数据称为df
,则可以:
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)))