[R] Replacing values of a matrix with values from corresponding rows of another matrix

Blaser Nello nblaser at ispm.unibe.ch
Mon Jul 15 08:40:14 CEST 2013


For small matrix you could use a for-loop.

for (i in 1:nrow(randomized)){
  randomized[i,randomized[i,]!=0] <- sample(original[i,original[i,]!=0])
}
randomized

If you have a larger matrix sapply is probably faster
randomized <- t(sapply(1:nrow(randomized), function(i) {
  randomized[i,randomized[i,]!=0] <- sample(original[i,original[i,]!=0])
  randomized[i,]
}))
randomized

Best, 
Nello

-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of Laura Cisneros
Sent: Montag, 15. Juli 2013 03:09
To: r-help at r-project.org
Subject: [R] Replacing values of a matrix with values from corresponding rows of another matrix

Hello all,

I have been trying to figure out how to replace non-zero values of a matrix with non-zero values from corresponding rows from another matrix. More specifically, let say we have the following original matrix:

original <-
matrix(c(0,0,4,0,0,1,2,2,12,1,0,2,0,5,0,0,10,1,3,1,0,5,0,4),byrow=TRUE,nrow=4,ncol=6)
> original
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    0    0    4    0    0    1
[2,]    2    2   12    1    0    2
[3,]    0    5    0    0   10    1
[4,]    3    1    0    5    0    4

And we randomize this matrix such that the total of occurrences of non-zero values in each row and column are maintained in the randomized matrix:

randomized <-
matrix(c(0,0,12,0,0,1,2,2,0,5,10,2,0,1,4,0,0,1,3,5,0,1,0,4),byrow=TRUE,nrow=4,ncol=6)
> randomized
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    0    0   12    0    0    1
[2,]    2    2    0    5   10    2
[3,]    0    1    4    0    0    1
[4,]    3    5    0    1    0    4

What I would like to do now is replace (in a random fashion) the non-zero values in each row of the randomized matrix using the non-zero values from the corresponding rows in the original matrix. For example, for row 1 I would like to randomly replace 12 and 1 (from the randomized matrix) with 4 and 1 (from the original matrix). Then do this for each row.

Any suggestions on how I may be able to accomplish this would be greatly appreciated.

Laura
--
Laura Cisneros, Doctoral Candidate
Dept. of Ecology and Evolutionary Biology University of Connecticut
75 N. Eagleville Road, U-3043
Storrs, CT 06269-3043

Tel: (860) 486-1772
Fax: (860) 486-5488
Alternative Email: laura.cisneros at uconn.edu

	[[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