[R] how can i count appearence of zero?

arun smartpink111 at yahoo.com
Tue Feb 11 08:56:13 CET 2014


Hi,
Try 

dat1<- as.matrix(read.table(text="V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
  6  6  6  6  6  0  0  0  0   0   0
  5  5  5  5  5  5  5  5  5   5   5
  1  0  0  0  0  0  0  0  0   0   0
  5  5  5  0  0  0  0  0  0   0   0
  6  8 11  0  9  0  0  0  0   0   0
  2  0  0  2  0  0  0  0  0   2   2",header=TRUE)) 
lst1 <- apply(!dat1,1,function(x) {r1 <- rle(x);r1$lengths[r1$values]})
mLen <- max(sapply(lst1,length))
res <- cbind(dat1,t(sapply(lst1,function(x) c(x,rep(NA,mLen-length(x))))))
colnames(res)[colnames(res)==""] <- paste0("Sum",seq(sum(colnames(res)=="")))
res
A.K.


Hi All, 

If you could help me with this problem I would greatly appreciate it. 

Suppose I have a matrix X 
     V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 
[1,]  6  6  6  6  6  0  0  0  0   0   0 
[2,]  5  5  5  5  5  5  5  5  5   5   5 
[3,]  1  0  0  0  0  0  0  0  0   0   0 
[4,]  5  5  5  0  0  0  0  0  0   0   0 
[5,]  6  8 11  0  9  0  0  0  0   0   0 
[6,]  2  0  0  2  0  0  0  0  0   2   2 

I would like to sum the number of times a 0 appears. So what I would like is to have 
                   Sum 
[1,]  6  6  6  6  6  0  0  0  0  0  0 6 NA
[2,]  5  5  5  5  5  5  5  5  5  5  5 NA NA
[3,]  1  0  0  0  0  0  0  0  0  0  0 10 NA
[4,]  5  5  5  0  0  0  0  0  0  0  0 8 NA
[5,]  6  8 11  0  9  0  0  0  0  0  0 1 6
[6,]  2  0  0  2  0  0  0  0  0  2  2 2 5
Thanks in advance.



More information about the R-help mailing list