[R] Random products of rows in a matrix

David Carlson dcarlson at tamu.edu
Wed Sep 4 16:34:50 CEST 2013


Actually you have two loops, the for() loop you created and the
loop that is hidden inside apply(). You can hide the first loop
with lapply() or sapply():

B <- do.call(rbind, lapply(1:N, function(x)
colSums(A[sample.int(nrow(A), M, replace=TRUE),])))

Or

B <- t(sapply(1:N, function(x) colSums(A[sample.int(nrow(A), M,
replace=TRUE),])))

You could eliminate the apply() loop by taking log(A), using
colSums(), and then converting back with exp().

-------------------------------------
David L Carlson
Associate Professor of Anthropology
Texas A&M University
College Station, TX 77840-4352

-----Original Message-----
From: r-help-bounces at r-project.org
[mailto:r-help-bounces at r-project.org] On Behalf Of Edouard Hardy
Sent: Wednesday, September 4, 2013 2:59 AM
To: R help
Subject: [R] Random products of rows in a matrix

Hello everybody,

Without any loop and any package,

I would like to return N products of M rows in a matrix A :

Today, I managed to do it with a loop :

B <- matrix(NA, ncol = ncol(A), nrow = 0)
for (i in 1 : N) B <- rbind(B, apply(A[sample(1 : nrow(A), M,
replace = T),
], 2, prod))

Do you have a solution ?

Thank you in advance !

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