使用之间的整数随机填充R datafame

时间:2018-05-05 22:18:32

标签: r dataframe random

我想用随机整数创建一个没有重复的R数据帧。

我提出了这种方法:

rank_random<-data.frame(matrix(NA, nrow = 13, ncol = 30)
for (colIdx in seq(1:30) {
rank_random[colIdx,] <-sample(1:ncol(subset(exc_ret, select=-c(Date))), 30, 
replace=F) 
}

1 个答案:

答案 0 :(得分:2)

我认为你的意思是不重复每一行。如果您有其他意思,请澄清。

对于你的例子:

N= ncol(subset(exc_ret, select=-c(Date)))
num.rows = 30
t(sapply( seq(num.rows), 
          FUN=function(x){sample(1:N, num.rows, replace=F)} ))

测试一个更简单的案例

N= 5
num.rows = 5
t(sapply( seq(num.rows), 
          FUN=function(x){sample(1:N, num.rows, replace=F)} ))

#      [,1] [,2] [,3] [,4] [,5]
# [1,]    2    4    5    1    3
# [2,]    2    5    1    3    4
# [3,]    5    1    4    3    2
# [4,]    3    4    5    2    1
# [5,]    3    2    5    1    4