[R] Sums based on values of other matrix
arun
smartpink111 at yahoo.com
Fri Sep 27 01:15:29 CEST 2013
Hi,
If you have missing values:
set.seed(125)
A<- matrix(sample(c(NA,0:9),10*10,replace=TRUE),10,10)
set.seed(49)
B<- matrix(sample(c(NA,1:25),10*10,replace=TRUE),10,10)
B1<- matrix(0,nrow=nrow(B),ncol=ncol(B))
B1[A==1 & !is.na(A)]<- B[A==1 & !is.na(A)]
rowSums(B1)
#[1] 0 0 38 7 16 0 0 1 6 18
#Speed comparison
set.seed(485)
Anew<- matrix(sample(c(NA,0:9),3e5*70,replace=TRUE),3e5,70)
set.seed(944)
Bnew<- matrix(sample(c(NA,1:25),3e5*70,replace=TRUE),3e5,70)
B2<- Bnew
B3<- matrix(0,nrow=nrow(Bnew),ncol=ncol(Bnew))
system.time({
B3[Anew==1 & !is.na(Anew)]<- Bnew[Anew==1 & !is.na(Anew)]
res1<- rowSums(B3)
})
# user system elapsed
# 2.916 0.308 3.232
system.time({
vec1<-ifelse(Anew == 1 & !is.na(Anew), B2, 0)
res2<- rowSums(vec1)
})
# user system elapsed
# 7.012 0.744 7.775
identical(res1,res2)
#[1] TRUE
A.K.
Dear Sarah,
this works very well! If fulfills what I need, however, there is
a small performance problem: I have 300.000 rows and 70 columns. With
missing values.
Besides that you directly hit the key.
Thanks,
Tobias
----- Original Message -----
From: arun <smartpink111 at yahoo.com>
To: tobias schlager <tobebryant at me.com>
Cc: R help <r-help at r-project.org>
Sent: Thursday, September 26, 2013 6:34 PM
Subject: Re: [R] Sums based on values of other matrix
Hi,
Try:
A<- structure(c(1, 2, 1, 2, 2, 1, 2, 1), .Dim = c(2L, 4L))
B<- structure(c(3, 1, 4, 1, 2, 2, 1, 2), .Dim = c(2L, 4L))
B1<- matrix(0,nrow(B),ncol(B))
B1[A==1]<-B[A==1]
rowSums(B1)
#[1] 7 4
A.K.
----- Original Message -----
From: tobias schlager <tobebryant at me.com>
To: "r-help at r-project.org" <r-help at r-project.org>
Cc:
Sent: Thursday, September 26, 2013 5:51 PM
Subject: [R] Sums based on values of other matrix
Dear all,
I have a big problem:
- I got two matrices, A and B
- A shows identifies the value of B, however the values of B must be summed
- For instance,
1 1 2 2
2 2 1 1
gives matrix a
3 4 2 1
1 1 2 2
gives matrix b
Now the result for the value 1 would be
7
4
which are the rowsums of the values of matrix B given that matrix A has the value 1.
How can I do this automatically? I am really puzzled here. Thanks for your help guys,
Tobi
[[alternative HTML version deleted]]
______________________________________________
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