R中的条件重新编码

时间:2017-07-26 17:19:04

标签: r recode

以下是R data.frame的摘录,其中包含指标。可以看出,对于某些行,指示符切换到1直到行的末尾,而其他行切换回零。

       [,18] [,19] [,20] [,21] [,22] [,23] [,24] 
   [1,]     0     0     0     0     0     0     0 
   [2,]     0     0     0     0     1     1     1  
   [6,]     0     0     0     0     0     0     0  
   [7,]     0     0     1     0     0     1     1  
   [8,]     0     0     0     0     0     0     0  
   [9,]     0     1     0     1     1     1     1  
  [10,]     1     1     1     1     1     1     1  
  [11,]     1     0     1     1     0     1     1

1的序列不再变回零到行的末尾时,我想识别每一行中的点。这应该由此后设置为1的所有元素指示,而前面的元素是0。结果将是:

       [,18] [,19] [,20] [,21] [,22] [,23] [,24] 
   [1,]     0     0     0     0     0     0     0 
   [2,]     0     0     0     0     1     1     1  
   [6,]     0     0     0     0     0     0     0  
   [7,]     0     0     0     0     0     1     1  
   [8,]     0     0     0     0     0     0     0  
   [9,]     0     0     0     1     1     1     1  
  [10,]     1     1     1     1     1     1     1  
  [11,]     0     0     0     0     0     1     1

1 个答案:

答案 0 :(得分:2)

您可以从每行末尾获取累计分钟数:

t(apply(m, 1, function(r) rev(cummin(rev(r)))))

#     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
#[1,]    0    0    0    0    0    0    0
#[2,]    0    0    0    0    1    1    1
#[3,]    0    0    0    0    0    0    0
#[4,]    0    0    0    0    0    1    1
#[5,]    0    0    0    0    0    0    0
#[6,]    0    0    0    1    1    1    1
#[7,]    1    1    1    1    1    1    1
#[8,]    0    0    0    0    0    1    1

数据:m是一个由1和0

组成的整数矩阵
dput(m)
structure(c(0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 
1L, 1L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 
1L, 1L, 1L, 0L, 1L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 1L, 0L, 1L, 0L, 
1L, 1L, 1L, 0L, 1L, 0L, 1L, 0L, 1L, 1L, 1L), .Dim = c(8L, 7L))