[R] calculating column difference in a matrix

Pedro Mardones mardones.p at gmail.com
Wed Mar 13 22:43:29 CET 2013


Dear R users;

Consider the following toy example:

a <- matrix(c(2,3,4,NA,NA,5,8,NA,8,NA), 5, 2)
b <- cbind(a,apply(a, 1, diff, na.rm = TRUE))

What I would like be able to get is:

c <- matrix(c(2,3,4,NA,NA,5,8,NA,8,NA,3,5,-4,8,NA), 5, 3)

i.e., for each row if both values (column 1 and 2) are NA then the
difference must return NA, but if any of those two values is different
from NA (!is.na), I would like to actually perform the difference
(something like assigning 0 instead to NA to the cell).

I'd appreciate any hint or comment

Best,

Pedro

BTW: the reason of this is that I'm trying to build an error checking
procedure for a big dataset I have



More information about the R-help mailing list