【发布时间】:2019-12-05 16:13:49
【问题描述】:
我想知道是否有更优雅的方式来获取数据帧,按x 分组以查看数据集中出现了多少 x,然后变异以查找每个 x 的第一次出现 (y)
test <- data.frame(x = c("a", "b", "c", "d",
"c", "b", "e", "f", "g"),
y = c(1,1,1,1,2,2,2,2,2))
x y
1 a 1
2 b 1
3 c 1
4 d 1
5 c 2
6 b 2
7 e 2
8 f 2
9 g 2
电流输出
output <- test %>%
group_by(x) %>%
summarise(count = n())
x count
<fct> <int>
1 a 1
2 b 2
3 c 2
4 d 1
5 e 1
6 f 1
7 g 1
期望的输出
x count first_seen
<fct> <int> <dbl>
1 a 1 1
2 b 2 1
3 c 2 1
4 d 1 1
5 e 1 2
6 f 1 2
7 g 1 2
我可以过滤test 数据框以查找第一次出现,然后使用left_join,但希望使用mutate 有更优雅的解决方案?
# filter for first occurrences of y
right <- test %>%
group_by(x) %>%
filter(y == min(y)) %>%
slice(1) %>%
ungroup()
# bind to the output dataframe
left_join(output, right, by = "x")
【问题讨论】:
-
您只需将该列添加到您的摘要中,将其设为
summarise(count = n(), first_seen = first(y))即可获得该输出。