mat mat - 4 years ago 89
R Question

Create dataframe from samples of a vector

Assume we have a vector

v <- 1:3
from which we want to generate a dataframe with 5 rows by applying the
sample
function to
v
. The expected results should be something like this:

X1 X2 X3
1 3 2
2 3 1
3 1 2
2 1 3
3 2 1


Note: It doesn't really matter if some rows are duplicated. I would prefer a solution that doesn't require a forloop.

Answer Source
v = 1:3
data.frame(matrix(sample(v, 5*length(v), replace = T), nrow = 5, ncol = length(v)))
#  X1 X2 X3
#1  3  3  1
#2  1  1  3
#3  3  3  1
#4  2  2  1
#5  3  1  2

# else 
data.frame(t(replicate(5, sample(v, length(v), replace = F))))
# else 
data.frame(t(sapply(1:5, function(x) sample(v, length(v), replace = F))))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download