如何 concat/combine 两个相同长度的矩阵到 "fill in the blanks" 其中一个矩阵?问题

How to concat/combine two matrices of the same length to "fill in the blanks" of one of the matrices? R Question

我正在做一个二进制整数编程作业,我希望有一个捷径可以输入所有的 1 和 0 作为约束。我创建了两个矩阵。第一个包含全零,第二个包含全一。

我有 34 个变量并创建了两个这样的矩阵(尽管我可能不需要创建这些):

zero_constraints = matrix(data = 0, nrow = 1, ncol = 34)
one_constraints = matrix(data = 1, nrow = 1, ncol = 34)

下面是一个约束示例:

# He therefore decides to include only one collage.
filter(data_raw, data_raw$Medium.Style == "Collage")$ID

输出:

[1]  9 16 29 30

我给每个变量一个数字,所以这些数字意味着我需要变量 9、16、29 和 30 为 1,其余变量为 0。

这是我迷路的地方:

one_constraints[, c(filter(data_raw, data_raw$Medium.Style == "Collage")$ID)]

我知道上面的行从我的 34 个矩阵中得到了我需要的 "ones" 所以我尝试连接我的两个矩阵 1 和 0:

cat(
    one_constraints[, c(filter(data_raw, data_raw$Medium.Style == "Collage")$ID)],
    zero_constraints[, -c(filter(data_raw, data_raw$Medium.Style == "Collage")$ID)]
)

输出:

1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

但这不是想要的输出。这些不应该在一开始就排成一行。它应该看起来像这样:

0    0    0    0    0    0    0    0    1     0     0     0     0     0     0     1     0     0   0     0    0     0     0    0     0     0     0     0     1     1     0     0     0     0

如果这太复杂了,我可以按照我最初的计划去 cbind 矩阵,这就是我创建上面的内容的方式。

如果你想要那个代码:

cbind(
  matrix(data = 0, nrow = 1, ncol = 8),     # 1-8
  1,                                        # 9
  matrix(data = 0, nrow = 1, ncol = 6),     # 10-15
  1,                                        # 16
  matrix(data = 0, nrow = 1, ncol = 12),    # 17
  1, 1,                                     # 29, 30
  matrix(data = 0, nrow = 1, ncol = 4)      # 31-34
)

编辑 我试过这个答案:

inds <- c(9, 16, 29, 30)
mat <- matrix(0, ncol = 34)
mat[, inds] <- 1

通过这样做:

twnety_one_con <- filter(data_raw, data_raw$Medium.Style == "Collage")$ID
twnety_one_mat <- matrix(data = 0, nrow = 1, ncol =34)
mat <- (twnety_one_mat[, twnety_one_mat] <- 1)

我可能做错了,但它不起作用。它 returns 一个 1 的向量,当我把它放在我的 add.constraint 位代码时,它确认它不匹配向量长度

您可以使用:

inds <- c(9, 16, 29, 30)
mat <- matrix(0, ncol = 34)
mat[, inds] <- 1

在 OP 函数中,filter 步骤 returns 中的索引表示列索引。我们只需要将 (<-) 的值赋值给 1

inds <- c(9, 16, 29, 30)
mat <- matrix(0, ncol = 34)
mat[, inds] <- 1


mat
#     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] #[,16] [,17] [,18] [,19] [,20] [,21] [,22] [,23] [,24]
#[1,]    0    0    0    0    0    0    0    0    1     0     0     0     0     0     0     #1     0     0     0     0     0     0     0     0
#     [,25] [,26] [,27] [,28] [,29] [,30] [,31] [,32] [,33] [,34]
#[1,]     0     0     0     0     1     1     0     0     0     0