为矩阵的每一行找到5个连续的数字> = 3

时间:2014-04-27 15:22:12

标签: r

我有以下矩阵

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个连续数字&gt; = 3并向txt文件写入初始数字和最终数字的位置,在示例第3行和第4行中有5个数字从第5列开始和7分别应该是:

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

以下解决方案几乎可以正常工作但是错过了第一个识别的行(第3行)的ini和final值

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)

2 个答案:

答案 0 :(得分:2)

如果您使用模式数字和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)

然后,您可以使用rle查找TRUE的{​​{1}}值序列:

x >= 3

答案 1 :(得分:1)

这与之前的答案略有不同,但我已经编写了代码,所以我想我也可以发布它。

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