R - dplyr:突变嵌套组无法按预期工作



我想根据数字是否偶数对数字列表进行分组,并计算偶数和奇数组。

suppressPackageStartupMessages(library(dplyr))
even <- function(x) return(! x %% 2)
df   <- group_nest(tibble(x = 1:9), even=even(x))

这有效:

# A tibble: 2 x 2
even                data
<lgl> <list<tbl_df[,1]>>
1 FALSE            [5 x 1]
2 TRUE             [4 x 1]

现在我想添加第三列,其中包含组的计数

mutate(df, count=nrow(data))

我期待以下结果:

# A tibble: 2 x 3
even                data  count
<lgl> <list<tbl_df[,1]>> <int>
1 FALSE            [5 x 1]      5
2 TRUE             [4 x 1]      4
> 

虽然,实际结果与原始数据帧相同,但未添加列,无错误,无任何内容。

手动检查:

nrow(df[[2]][[1]])
[1] 5
nrow(df[[2]][[2]])
[1] 4
可以使用

mutate(df, count=map_dbl(data, nrow))
# A tibble: 2 x 3
even                data count
<lgl> <list<tbl_df[,1]>> <dbl>
1 FALSE            [5 x 1]     5
2 TRUE             [4 x 1]     4

最新更新