【问题标题】:How can we add two matrices with different rows and columns in R?我们如何在 R 中添加两个具有不同行和列的矩阵?
【发布时间】:2019-03-03 05:46:55
【问题描述】:

我有两个矩阵:例如

temp1 <- matrix(c(1,2,3,4,5,6),2,3,byrow = T)
temp2 <- matrix(c(7,8,9),1,3,byrow = T)

温度1

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

温度2

       [,1] [,2] [,3]
 [1,]    7    8    9

我有两个行数相同但行数不同的矩阵。我想将这两个矩阵添加如下。我想知道是否有一种方法可以在没有 for 语句和应用函数的情况下添加 R。

temp <- do.call(rbind,lapply(1:2,function(x){temp[x,]+temp2}))

温度

       [,1] [,2] [,3]
 [1,]    8   10   12
 [2,]   11   13   15

这个例子很简单,但实际上我需要用一个 100 * 100 的矩阵和一个 1 * 100 的矩阵来做上面的事情。在这种情况下,耗时太长,所以我不想使用 for 语句和 apply 函数。

【问题讨论】:

  • 您可以转置100x100矩阵,使用t,然后将1*100矩阵与as.numeric相加,然后转置结果。即t(t(temp1) + as.numeric(temp2))
  • 或者,您可以将后者扩展为与前者相同的形状:temp1 + temp2[rep(1, nrow(temp1)), ]

标签: r matrix sum col


【解决方案1】:

你可以使用?sweep:

temp1 <- matrix(c(1,2,3,4,5,6),2,3,byrow = T)
temp2 <- matrix(c(7,8,9),1,3,byrow = T)
sweep(temp1, 2, temp2, '+')

不幸的是,sweep 的帮助很难理解,但是在这个例子中,你沿着 temp1 的第二维应用了函数 ´+´ 和参数 ´temp2´。

更多示例请见:How to use the 'sweep' function

【讨论】:

  • 感谢您的知识。这对我帮助很大!
猜你喜欢
  • 2013-10-20
  • 1970-01-01
  • 1970-01-01
  • 2014-09-09
  • 2017-04-08
  • 1970-01-01
  • 2019-08-12
  • 1970-01-01
  • 2020-10-27
相关资源
最近更新 更多