Skip to content
Prev 313804 / 398525 Next

Why does matrix selection behave differently when using which?

On 17-12-2012, at 21:03, Asis Hallab wrote:

            
Use this alternative sumRows

sumRows.1 <- function( tbl, ps ) {
 sum(
   sapply(ps,
     function(x) {
       t <- if ( is.na(x) ) {
         tbl[ is.na(tbl[ , "Domain.Architecture.Distance" ] ), ,drop=F]
       } else {
		# explicit check for NA
         tbl[ !is.na(tbl[ , "Domain.Architecture.Distance" ]) & tbl[ , "Domain.Architecture.Distance" ] == x , ,drop=F]
       }
       nrow(t)
     }
   )
 )
}

z <- sort( unique( t[,"Domain.Architecture.Distance"] ) )

sumRows(t,z)
sumRows.1(t,z)

You must check with is.na() when not using which.
More insight can be gained by reading the help for Logical operators.
Try

?'!'

and read the bit about NA.
I'm too lazy to check if the modifcation with !is.na completely accounts for the difference between  the which and the not which versions.

And please don't use t as an object name.

Berend