简体   繁体   中英

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.

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))))

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
dfV <- data.frame(v1 = sample(v, 5,replace = TRUE), v2 = sample(v, 5, replace = TRUE), v3 = sample(v, 5, replace = TRUE))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM