每年有两组,第一组在第二组之上。我想添加一个列,表示行所在的组:第一个或第二个。我为此示例标记了组,但该字段未出现在真实数据集中。
year measure data ...
1991 1 ... [group 1]
1991 2 [group 1]
1991 3 [group 1]
1991 1 [group 2]
1991 2 [group 2]
1991 3 [group 2]
1991 4 [group 2]
1992 1 [group 1]
1992 2 [group 1]
1992 3 [group 1]
1992 1 [group 2]
1992 2 [group 2]
1992 3 [group 2]
1992 4 [group 2]
答案 0 :(得分:1)
我们可以尝试使用data.table
,dplyr
或base R
方法。使用data.table
,我们将'data.frame'转换为'data.table'(setDT(df1)
),按'年'分组,我们检查'measure'的相邻元素的差异是否小于0 ,得到累积总和,并paste
与'group'一起创建'grp'列。
library(data.table)
setDT(df1)[, grp := paste("group", cumsum(c(TRUE, diff(measure) < 0))), year]
df1
# year measure grp
#1: 1991 1 group 1
#2: 1991 2 group 1
#3: 1991 3 group 1
#4: 1991 1 group 2
#5: 1991 2 group 2
#6: 1991 3 group 2
#7: 1991 4 group 2
#8: 1992 1 group 1
#9: 1992 2 group 1
#10:1992 3 group 1
#11:1992 1 group 2
#12:1992 2 group 2
#13:1992 3 group 2
#14:1992 4 group 2
可以在dplyr
library(dplyr)
df1 %>%
group_by(year) %>%
mutate(grp = paste("group", cumsum(c(TRUE, diff(measure) < 0))))