I have a matrix with 12 rows and 77 columns, but to simply lets use:
p <- matrix(NA,5,7)
p[1,2]<-0.3
p[1,3]<-0.5
p[2,4]<-0.9
p[2,7]<-0.4
p[4,5]<-0.6
I want to know which columns are not “NA” per row, so what I would like to get would be something like:
[1] 2,3
[2] 4
[3] 0
[4] 5
[5] 0
but if I do > which(p[]!="NA") I get [1] 6 11 17 24 32
I tried using a loop:
aux <- matrix(NA,5,7)
for(i in 1:5) {
aux[i,]<-which(p[i,]!="NA")
}
but I just get an error: number of items to replace is not a multiple of replacement length
Is there a way of doing this? Thanks in advance
Try:
Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:
Or even with smushing together with paste:
The output from
whichfunction the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:Without the
arr.indparameter set to non-default TRUE, you only get the “vector location” determined using the column major ordering the R has as its convention. R-matrices are just “folded vectors”.