Reputation: 2617
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.
Upvotes: 2
Views: 142
Reputation: 23
dfV <- data.frame(v1 = sample(v, 5,replace = TRUE), v2 = sample(v, 5, replace = TRUE), v3 = sample(v, 5, replace = TRUE))
Upvotes: 0
Reputation: 37879
I think pryr
's %<a-%
operator is great for this. %<a-%
saves an expression to a variable, but every time the variable is evaluated the expression is rerun. Perfect for sampling:
library(pryr)
#the function sample will be rerun each time sampled is evaluated
sampled %<a-% sample(v)
#replicate just replicates an expression
#t pivots the matrix, so that you get the output you want
data.frame(t(replicate(5, sampled)))
#or simply (since the edit makes it simpler)
#data.frame(t(replicate(5, sample(v))))
Output:
X1 X2 X3
1 3 1 2
2 2 1 3
3 1 3 2
4 2 3 1
5 2 3 1
Upvotes: 3
Reputation: 8413
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))))
Upvotes: 3