减去不同维度的矩阵

时间:2018-03-10 11:20:36

标签: r

我的matix B有100行3列,矩阵C有100行1列。我想创建一个包含100行和3列的矩阵A,如下所示

A <- B - C

新矩阵A中的第一行:

A[1,1] <- B[1,1]-C[1,1] 

A[1,2] <- B[1,2]-C[1,1] 

A[1,3] <- B[1,3]-C[1,1]

运行此代码时出现以下错误消息:

  

B-C中的错误:不一致的数组

2 个答案:

答案 0 :(得分:2)

申请救援

set.seed(123)
B <- matrix(sample(1:30), ncol = 3)
C <- matrix(sample(1:10), ncol = 1)
A <- apply(B, 2, `-`, C)
A
#      [,1] [,2] [,3]
# [1,]   -1   10    9
# [2,]   14   21   -2
# [3,]    6   16    0
# [4,]   16   21    9
# [5,]   24   25   27
# [6,]   -1   11    5
# [7,]    9    0   -1
# [8,]   14   -6    9
# [9,]   22   10   13
#[10,]    8    9    3

答案 1 :(得分:0)

我们可以将'C'强制转换为'向量,然后进行减法

A <- B - c(C)
A
#      [,1] [,2] [,3]
# [1,]   -1   10    9
# [2,]   14   21   -2
# [3,]    6   16    0
# [4,]   16   21    9
# [5,]   24   25   27
# [6,]   -1   11    5
# [7,]    9    0   -1
# [8,]   14   -6    9
# [9,]   22   10   13
#[10,]    8    9    3

as.vector

A <- B - as.vector(C)

数据

set.seed(123)
B <- matrix(sample(1:30), ncol = 3)
C <- matrix(sample(1:10), ncol = 1)