See below
On Wed, 29 Apr 2009, Silvia Lomascolo wrote:
Hi R community,
I am trying to obtain a sample from a matrix but sample(my.matrix) doesn't
do what I need. I have a matrix of 1287 interactions between the species in
columns and the species in rows and I want to obtain a smaller matrix with
say, 800 interactions, that may or may not have the same number of columns
and/or rows (i.e., some interactions may not be retrieved in a smaller
sample). For example, my original mock matrix M is
[,1] [,2] [,3] [,4] [,5]
[1,] 140 100 90 40 20
[2,] 126 90 81 36 18
[3,] 84 60 54 24 12
[4,] 70 50 45 20 10
[5,] 42 30 27 12 6
The command sample(my.matrix) samples whole cells from my matrix, such that
if the interaction between species 1 and 1 is included in the sample, they
always show 140 interactions. But what I want is to sample "cases" within
each cell. My sample matrix S could have =<140 interactions between species
1 and 1, =<100 between species 1 and 2, etc. Again, if some combination is
absent from the sample matrix, that's OK.
Here's my code, in case it helps:
pla<- c(10, 9, 6, 5, 3) #abundance of pla species
pol<- c(14, 10, 9, 4, 2) #abundance of pol species
m<-pla%*%t(pol) #matrix of interactions according to pla and pol abundance
m
[,1] [,2] [,3] [,4] [,5]
[1,] 140 100 90 40 20
[2,] 126 90 81 36 18
[3,] 84 60 54 24 12
[4,] 70 50 45 20 10
[5,] 42 30 27 12 6
sample(m) #doesn't give me what I want...
If I understand you,
m.index <- 1:length(m)
# sample all 1287:
new.m <- matrix(table( factor( sample(rep(m.index,m),1287), m.index )),nr=5)
all.equal(m, new.m) # verify that original was reproduced
[1] TRUE
# now sample just 800
new.m <- matrix(table( factor( sample(rep(m.index,m),800), m.index
)),nr=5)
m-new.m # look at the difference
Chuck
I have searched the forum for an answer but all questions regarding sampling
from matrices refer to sampling whole rows or columns, not "cases" within a
matrix.
Thanks in advance for any help! Silvia.
--
View this message in context:
http://www.nabble.com/How-do-I-sample-%22cases%22-within-a-matrix--tp23296664p23296664.html
Sent from the R help mailing list archive at Nabble.com.
______________________________________________
R-help@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.
Charles C. Berry (858) 534-2098
Dept of Family/Preventive Medicine
E mailto:cbe...@tajo.ucsd.edu UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/ La Jolla, San Diego 92093-0901
______________________________________________
R-help@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.