使用dplyr和add_row()在每个组中添加行 [英] Add row in each group using dplyr and add_row()
问题描述
如果我向ìris
数据集添加新行,则使用以下命令:
If I add a new row to the ìris
dataset with:
iris <- as_tibble(iris)
> iris %>%
add_row(.before=0)
# A tibble: 151 × 5
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
<dbl> <dbl> <dbl> <dbl> <chr>
1 NA NA NA NA <NA> <--- Good!
2 5.1 3.5 1.4 0.2 setosa
3 4.9 3.0 1.4 0.2 setosa
它作品。因此,为什么我不能在每个子集的顶部添加新行:
It works. So, why can't I add a new row on top of each "subset" with:
iris %>%
group_by(Species) %>%
add_row(.before=0)
Error: is.data.frame(df) is not TRUE
推荐答案
如果要使用分组操作,则需要 do像JasonWang在评论中所述的
,因为 mutate
或 summarise
之类的其他函数希望得到结果与分组数据框的行数相同(在您的情况下为50),或与行的数量相同(例如,汇总时)。
If you want to use a grouped operation, you need do
like JasonWang described in his comment, as other functions like mutate
or summarise
expect a result with the same number of rows as the grouped data frame (in your case, 50) or with one row (e.g. when summarising).
如您所知,通常 do
可能会很慢,如果您无法实现自己的目标,那应该是最后的选择以另一种方式导致。您的任务非常简单,因为它只涉及在数据帧中添加额外的行,这可以通过简单的索引来完成,例如查看 iris [NA,]
的输出。
As you probably know, in general do
can be slow and should be a last resort if you cannot achieve your result in another way. Your task is quite simple because it only involves adding extra rows in your data frame, which can be done by simple indexing, e.g. look at the output of iris[NA, ]
.
您想要的本质上是创建向量
What you want is essentially to create a vector
indices <- c(NA, 1:50, NA, 51:100, NA, 101:150)
(因为第一组在第1至50行中,第二组在51至100行中,第三组在101行中至150)。
(since the first group is in rows 1 to 50, the second one in 51 to 100 and the third one in 101 to 150).
结果为 iris [indices,]
。
构建此向量的更通用方法是使用 group_indices
。
A more general way of building this vector uses group_indices
.
indices <- seq(nrow(iris)) %>%
split(group_indices(iris, Species)) %>%
map(~c(NA, .x)) %>%
unlist
( map
来自 purrr
,我认为您已经加载了该文件,因为您已经用 tidyverse标记了它
)。
(map
comes from purrr
which I assume you have loaded as you have tagged this with tidyverse
).
这篇关于使用dplyr和add_row()在每个组中添加行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!