[R] Sampling from a Matrix
Daniel Gerlanc
dgerlanc at gmail.com
Fri Aug 4 18:46:15 CEST 2006
Hello all,
Consider the following problem:
There is a matrix of probabilities:
> set.seed(1)
> probs <- array(abs(rnorm(25, sd = 0.33)), dim = c(5,5), dimnames = list(1:5, letters[1:5]))
> probs
a b c d e
1 0.21 0.27 0.50 0.0148 0.303
2 0.06 0.16 0.13 0.0053 0.258
3 0.28 0.24 0.21 0.3115 0.025
4 0.53 0.19 0.73 0.2710 0.656
5 0.11 0.10 0.37 0.1960 0.205
I want to sample 3 values from each row.
One way to do this follows:
index <- 1:ncol(probs)
for(i in 1:nrow(probs)){
## gets the indexes of the values chosen
sample(index, size = 3, replace = TRUE, prob = probs[i, ])
}
Is there a another way to do this?
Thanks!
Dan Gerlanc
--
Daniel Gerlanc
Williams College '07
More information about the R-help
mailing list