【发布时间】:2017-07-28 00:15:25
【问题描述】:
下面的代码应该按年份对数据进行分组,然后使用每年的第一个值和最后一个值创建两个新列。
library(dplyr)
set.seed(123)
d <- data.frame(
group = rep(1:3, each = 3),
year = rep(seq(2000,2002,1),3),
value = sample(1:9, r = T))
d %>%
group_by(group) %>%
mutate(
first = dplyr::first(value),
last = dplyr::last(value)
)
但是,它不能正常工作。预期的结果是
group year value first last
<int> <dbl> <int> <int> <int>
1 1 2000 3 3 4
2 1 2001 8 3 4
3 1 2002 4 3 4
4 2 2000 8 8 1
5 2 2001 9 8 1
6 2 2002 1 8 1
7 3 2000 5 5 5
8 3 2001 9 5 5
9 3 2002 5 5 5
然而,我明白了(它需要整个数据框的第一个和最后一个值,而不仅仅是组):
group year value first last
<int> <dbl> <int> <int> <int>
1 1 2000 3 3 5
2 1 2001 8 3 5
3 1 2002 4 3 5
4 2 2000 8 3 5
5 2 2001 9 3 5
6 2 2002 1 3 5
7 3 2000 5 3 5
8 3 2001 9 3 5
9 3 2002 5 3 5
【问题讨论】:
-
它适用于我:我得到一列,其中包含按组的第一个值和一个按组包含最后一个值的列。
-
能否显示
dplyr的版本 -
你想要
summarize而不是变异吗? -
我的猜测是duplicate of this,您无意中使用了
plyr::mutate而不是dplyr::mutate。然而,“没有按预期工作”的描述如此模糊,以至于无法知道...... -
谢谢大家! @Gregor 解决了这个问题!另外,我已经更新了这个问题,使预期结果与实际结果更准确。
标签: r dplyr data-manipulation