我有一个数据框,其中的变量将观察值(ID)分组,另一个变量是分类的(type)。我正在R中工作,正在尝试创建一个新变量,该变量计算ID(数据是时间序列)中同一类型的连续观察值。请参阅下面的示例表-计数器是我要创建的变量。是否计数为0并不重要。
dat <- data.frame(id = c(rep("a", 7), rep("b", 4)),
type = c(0, 1, 1, 2, 2, 0, 1, 1, 1, 2, 0),
counter = c(0, 1, 2, 1, 2, 0, 1, 1, 2, 1, 0))
到目前为止,我虽然无法以最有效的方式进行计数,但仍在分组(ID)中进行此操作并有效地在type = 1和type = 2之间切换。计数器在下面。关于如何有效执行此操作的任何想法?谢谢。
dat$counter <- 0
counter <- 0
for(i in 1:nrow(dat)){
if(dat[i,"type"] != 0){
counter <- counter + 1
dat[i,"count"] <- counter
# use to differentiate between 1 and 2?
this_group <- dat[i,"type"]
}
if(dat[i,"type"] == 0){
counter <- 0
}
}
对于每一个id
,type
并开始连续的行type
0使用创建一个序列ave
和seq_along
。不使用任何软件包:
transform(dat,
counter = (type > 0) * ave(type, id, type, cumsum(type == 0), FUN = seq_along))
给予:
id type counter
1 a 0 0
2 a 1 1
3 a 1 2
4 a 2 1
5 a 2 2
6 a 0 0
7 a 1 1
8 b 1 1
9 b 1 2
10 b 2 1
11 b 0 0
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句