Pages

7/05/2011

Demonstration of random sampling

(1) Sampling without replacement:use function combinations in the package gtools

For example:
library(gtools)
y = c(1,2,4,6,7,10,7,8)
perm = combinations(8,3) # eumerate all the possible combinations
prob = rep(1/56,dim(perm)[1]) # total 56 combinations
samples = apply(perm, 1, function(x) {sum(y[x])})
tab = table(samples)
result = tab*1/56


(2) Sampling with replacement: use function expand.grid available in the base package.

For example:

replace = expand.grid(rep(list(1:8),3)) # all possible samples with replacement
samples = apply(replace, 1, function(x) {sum(y[x])})
tab = table(samples)
result = tab*1/(8^3) # total 8^3 possible combinations

No comments:

Post a Comment