![](/img/trans.png)
[英]How to find number of observation between first observation and first two consecutive negative observations in r
[英]combine similar consecutive observations into one observation in R
我有這樣的數據集
date ID key value
05 1 3 2
05 1 3 5
05 1 3 1
05 1 5 2
05 1 7 3
05 1 7 3
05 1 3 4
05 2 9 8
我需要輸出看起來像這樣
date ID key value
05 1 3 8
05 1 5 2
05 1 7 6
05 1 3 4
05 2 9 8
因此,如您所見, 連續的日期,ID和鍵是否相同,我想知道如何結合這些觀察結果並增加其值。 僅當事件連續發生時,我才需要執行此操作。 有可能這樣做嗎? 如果是,有人可以告訴我該怎么做嗎? 謝謝
使用rle
查找連續序列
# your data
df <- read.table(text="date ID key value
05 1 3 2
05 1 3 5
05 1 3 1
05 1 5 2
05 1 7 3
05 1 7 3
05 1 3 4
05 2 9 8", header=T)
# get consecutive values - add a grouping variables
r <- with(df, rle(paste(date, ID, key)))
df$grps <- rep(seq(r$lengths), r$lengths)
# aggregate values
a <- aggregate(value ~ date + ID + key + grps, data = df , sum)
# remove the grouping variable
a$grps <- NULL
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.