r查找5个连续数字>=对于矩阵的每一行为3



我有以下矩阵

mdat <- matrix(c(6,2,4,4,'*',5,1,6,'*',2,1,5,1,3,3,5,4,'*',5,'*',1,'*',4,'*',2,2,4,3,4,4,4,'*',4,3,3,1,1,3,2,3,3,3,3,3,2,2,'*','*',2,1,2,2,2,2,2,1,1,1,1,1,'*',1,1,1,1,1 ),nrow = 6, ncol = 11, byrow = TRUE)

[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]
[1,] "6"  "2"  "4"  "4"  "*"  "5"  "1"  "6"  "*"  "2"   "1"  
[2,] "5"  "1"  "3"  "3"  "5"  "4"  "*"  "5"  "*"  "1"   "*"  
[3,] "4"  "*"  "2"  "2"  "4"  "3"  "4"  "4"  "4"  "*"   "4"  
[4,] "3"  "3"  "1"  "1"  "3"  "2"  "3"  "3"  "3"  "3"   "3"  
[5,] "2"  "2"  "*"  "*"  "2"  "1"  "2"  "2"  "2"  "2"   "2"  
[6,] "1"  "1"  "1"  "1"  "1"  "*"  "1"  "1"  "1"  "1"   "1"  

我试图为每一行找到5个连续的数字>=3,并将初始数字和最终数字的位置写入txt文件,在示例中,第3行和第4行分别有5个数字从第5列和第7列开始,应该是:

initial = [3,5] final [3,9]
initial = [4,7] final [4,11]

下面的解决方案几乎有效,但错过了第一个识别行(第3行)的ini和最终值

element<-0
ini<-1
final<-1
consecutives<-0
zz<-file("C:/consecutives.txt","w")
for (i in 1:6){
for (j in 1:11) {
 if (b[i,j] != "*"){
    element<-as.integer(b[i,j])
       if (element>=3)
     {ini<-j
          consecutives<-consecutives+1
      row<-i 
      if (consecutives>=5){
         final<-j
        writeLines(paste("element",toString(element), "Row", toString(row),  "ini", toString(ini),"final",toString(final)) ,con=zz,sep = "n")
     }
      }

  }
else consecutives<-0
}
}
close(zz)

如果使用模式数字和NA而不是"*":,处理起来会更容易

 mdat <- matrix(c(6,2,4,4,NA,5,1,6,NA,2,1,5,1,3,3,5,4,NA,5,NA,1,NA,4,NA,2,2,4,3,4,4,4,NA,4,3,3,1,1,3,2,3,3,3,3,3,2,2,NA,NA,2,1,2,2,2,2,2,1,1,1,1,1,NA,1,1,1,1,1 ),nrow = 6, ncol = 11, byrow = TRUE)

然后可以使用rlex >= 3:查找TRUE值的序列

apply(mdat, 1, function(x) {
  r <- rle(x >= 3)
  w <- which(!is.na(r$values) & r$values & r$lengths > 4)
  if (length(w) > 0) {
    before <- sum(r$lengths[1:(w[1]-1)])
    c(before+1,before+ r$lengths[w[1]])
  } else
    NULL
})
[[1]]
NULL
[[2]]
NULL
[[3]]
[1] 5 9
[[4]]
[1]  7 11
[[5]]
NULL
[[6]]
NULL

这与之前的答案只有一点不同,但我已经写了代码,所以我想我还不如发布它。

foo = function(x) {
  bb = rle( x >= 3 )
  bb$values = bb$lengths>4 & bb$values
  range( which(inverse.rle(bb)))
}
out = apply(mdat,1,foo)
out[ is.infinite(out) ] = NA
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]   NA   NA    5    7   NA   NA
[2,]   NA   NA    9   11   NA   NA

最新更新