[R] calculating column difference in a matrix
arun
smartpink111 at yahoo.com
Wed Mar 13 23:05:10 CET 2013
Hi,
Try this:
a1<-a
a1[rowSums(is.na(a1))==1][ is.na(a1[rowSums(is.na(a1))==1])]<-0
library(matrixStats) c1<- cbind(a,rowDiffs(a1))
c1
# [,1] [,2] [,3]
#[1,] 2 5 3
#[2,] 3 8 5
#[3,] 4 NA -4
#[4,] NA 8 8
#[5,] NA NA NA
identical(c,c1)
#[1] TRUE
A.K.
----- Original Message -----
From: Pedro Mardones <mardones.p at gmail.com>
To: R-help at r-project.org
Cc:
Sent: Wednesday, March 13, 2013 5:43 PM
Subject: [R] calculating column difference in a matrix
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
______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list