【问题标题】:Calculate a variable based on length of run of specific value in R code根据R代码中特定值的运行长度计算变量
【发布时间】:2015-03-23 05:03:26
【问题描述】:

我有一个这样的数据集,

 dat <- data.frame(d1=c(0,1,0,1,0),
      d2=c(0,1,1,1,0),d3=c(1,0,1,1,0),
      d4=c(1,0,0,0,0),d5=c(1,1,1,0,0))
 dat
  d1 d2 d3 d4 d5
1  0  0  1  1  1
2  1  1  0  0  1
3  0  1  1  0  1
4  1  1  1  0  0
5  0  0  0  0  0

如果我认为每一行都是针对个人的一组跑步。我想根据运行计算一个名为“indicator”的指标变量。例如,个体 1 运行是 (0,0,1,1,1),因为这个反向长度的运行,值第一个 1 是 3。另一方面,对于个体 3 运行是 (0,1,1,0, 1),值前1,s的向后运行长度为1。所需的数据集是这样的。

  d1 d2 d3 d4 d5 indicator
   0  0  1  1  1   3
   1  1  0  0  1   1
   0  1  1  0  1   1
   1  1  1  0  0   3 
   0  0  0  0  0   0

这种方式我试过了,

    indicator <- NULL      
    for(i in 1:5){
        indicator[i] <- rev(sequence(rle(dat[i,])$lengths))[1]
     }
    indicator[1:5]
   cbind(dat, indicator=indicator[1:5])

但这给出了这样的数据,

  d1 d2 d3 d4 d5 indicator
1  0  0  1  1  1         3
2  1  1  0  0  1         1
3  0  1  1  0  1         1
4  1  1  1  0  0         2
5  0  0  0  0  0         5

谁能帮我解决这个问题?

【问题讨论】:

    标签: r run-length-encoding


    【解决方案1】:

    试试

    val <- apply(dat, 1, function(x) with(rle(rev(x)==1), lengths[values])[1])
    dat$indicator <- replace(val, is.na(val),0)
    dat
    #   d1 d2 d3 d4 d5 indicator
    #1  0  0  1  1  1         3
    #2  1  1  0  0  1         1
    #3  0  1  1  0  1         1
    #4  1  1  1  0  0         3
    #5  0  0  0  0  0         0
    

    【讨论】:

      【解决方案2】:

      另一种方法:

      x = apply(rev(dat),1, function(u) ifelse(u[1]==1, match(0,u)-1, match(1,u)))
      transform(dat, indicator = ifelse(is.na(x), 0,x))
      
      #  d1 d2 d3 d4 d5 indicator
      #1  0  0  1  1  1         3
      #2  1  1  0  0  1         1
      #3  0  1  1  0  1         1
      #4  1  1  1  0  0         3
      #5  0  0  0  0  0         0
      

      【讨论】:

      • 没错,我尝试了其他带有矢量化解决方案矩阵的解决方案并保留了命令!已编辑。
      猜你喜欢
      • 1970-01-01
      • 2017-03-07
      • 2013-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-26
      • 1970-01-01
      相关资源
      最近更新 更多