创建一个随组变量的每次变化而递增的数字序列的有效方法是什么?作为一个玩具示例,使用下面的数据框,我希望一个新变量“值”具有值c(1,1,1,2,2,3,3,4)
。请注意,即使48重复自身,“值”仍然增加,因为我只关心序列中的变化。
df <- read.table(textConnection(
'Group
48
48
48
56
56
48
48
14'), header = TRUE)
一种方法是
df$Value<-1
for(i in 2:nrow(df)){
if(df[i,]$Group==df[i-1,]$Group){df[i,]$Value=df[i-1,]$Value}
else{df[i,]$Value=df[i-1,]$Value+1}
}
但这是非常慢的。我的实际数据集有几百万个观测值。
**注:**我很难确定此问题的标题,如果您愿意,请更改标题。
4条答案
按热度按时间5lhxktic1#
我们也可以黑进
rle
。数据
pcww981p2#
灵感来自这篇文章:https://stackoverflow.com/a/44512144/3772141
就这么办吧:
结果:
工作原理:
1.将
Value
与上一行的Value
进行比较。如果它发生变化,则将其设置为TRUE
,在此指示开始一个新值:Group != lag(Group)
NA
,但对于第一行,它应该始终是TRUE
:| row_number() == 1
TRUE
和FALSE
可以表示为1
和0
,因此使用cumsum
函数时,只要内部表达式返回TRUE
,Group
发生变化,Value
就会递增。pvabu6sv3#
不如
zzzyeukh4#
如果你在tidyverse中,
dplyr 1.1.0
有一个函数consecutive_id()
,它可以完全满足你的需求!tidyverse团队推荐它用于Zoom通话记录,在这种情况下,同一个说话人的连续几行应该被归为一个单独的想法:https://www.tidyverse.org/blog/2023/02/dplyr-1-1-0-vctrs/#consecutive_id