在R?中对分类变量的连续观察中添加计数器

布德森

我有一个数据框,其中的变量将观察值(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
  }
}
G.格洛腾迪克

对于每一个idtype并开始连续的行type0使用创建一个序列aveseq_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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章