从矢量样本创建数据帧

时间:2017-02-05 18:50:58

标签: r

假设我们有一个向量v <- 1:3,我们希望通过将sample函数应用到v来生成一个包含5行的数据帧。预期结果应该是这样的:

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

注意:如果某些行重复,则无关紧要。我更喜欢不需要forloop的解决方案。

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:3)

我认为pryr&#39; %<a-%运算符非常适合这一点。 %<a-%将表达式保存到变量中,但每次计算变量时,表达式都会重新运行。非常适合采样:

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

输出:

  X1 X2 X3
1  3  1  2
2  2  1  3
3  1  3  2
4  2  3  1
5  2  3  1

答案 2 :(得分:0)

dfV <- data.frame(v1 = sample(v, 5,replace = TRUE), v2 = sample(v, 5, replace = TRUE), v3 = sample(v, 5, replace = TRUE))