使用R中的向量随机填充矩阵的列

时间:2018-06-12 11:41:47

标签: r matrix

我需要按列填充下面的矩阵,并随机选择变量hub中包含的值。

hub <- c(1) # there can be only one '1' per column.
for(i in 1:(49)){
  no <- 0
  hub <- c(hub,no)
}

matriz_hubs <- matrix(data = sample(hub),nrow = 50,ncol = hub_total,byrow = FALSE)

虽然此代码有效,但它会将所有“1”值放在同一行上。有没有办法可以随机选择每列的值?

1 个答案:

答案 0 :(得分:3)

试试这个:

set.seed(1)
mat <- do.call("cbind", lapply(1:5, function(x) sample(c(1, rep(0, 49)), 50)))

> mat
      [,1] [,2] [,3] [,4] [,5]
 [1,]    0    0    0    0    0
 [2,]    0    0    0    0    0
 [3,]    0    0    0    0    0
 [4,]    0    0    0    0    0
 [5,]    0    0    0    0    0
 [6,]    0    0    0    0    0
 [7,]    0    0    0    0    0
 [8,]    0    0    0    0    0
 [9,]    0    0    0    0    0
[10,]    0    0    0    0    0
[11,]    0    0    0    0    0
[12,]    0    0    0    0    0
[13,]    0    0    0    0    0
[14,]    0    0    0    0    0
[15,]    0    0    0    0    0
[16,]    0    0    1    0    0
[17,]    0    0    0    0    0
[18,]    0    0    0    0    0
[19,]    0    0    0    0    0
[20,]    0    0    0    0    0
[21,]    0    0    0    0    0
[22,]    0    0    0    0    0
[23,]    0    0    0    0    0
[24,]    0    0    0    0    0
[25,]    0    0    0    0    0
[26,]    0    0    0    0    0
[27,]    1    0    0    0    0
[28,]    0    0    0    0    0
[29,]    0    0    0    0    0
[30,]    0    0    0    0    0
[31,]    0    0    0    0    0
[32,]    0    0    0    0    0
[33,]    0    0    0    0    0
[34,]    0    0    0    0    0
[35,]    0    0    0    0    0
[36,]    0    0    0    0    0
[37,]    0    0    0    0    0
[38,]    0    0    0    0    0
[39,]    0    0    0    0    0
[40,]    0    0    0    0    0
[41,]    0    0    0    0    0
[42,]    0    1    0    0    0
[43,]    0    0    0    1    0
[44,]    0    0    0    0    1
[45,]    0    0    0    0    0
[46,]    0    0    0    0    0
[47,]    0    0    0    0    0
[48,]    0    0    0    0    0
[49,]    0    0    0    0    0
[50,]    0    0    0    0    0

您可以将5 1:5中的lapply更改为您想要的值,从而选择更多或更少的列。

你甚至可以写一个函数:

BUILDMAT <- function(nrow, ncol){
  mat <- do.call("cbind", lapply(1:ncol, function(x) sample(c(1, rep(0, nrow-1)), nrow)))
  return(mat)
}

现在就这样称呼:

test <- BUILDMAT(10, 5)

> test
      [,1] [,2] [,3] [,4] [,5]
 [1,]    0    0    1    1    0
 [2,]    0    0    0    0    0
 [3,]    0    0    0    0    0
 [4,]    0    0    0    0    0
 [5,]    0    0    0    0    0
 [6,]    1    1    0    0    0
 [7,]    0    0    0    0    1
 [8,]    0    0    0    0    0
 [9,]    0    0    0    0    0
[10,]    0    0    0    0    0