考虑到仅有一行的矩阵,在R中划分两个矩阵

时间:2014-01-14 15:21:49

标签: r

大家好我正在使用R中的矩阵,我试图在3x3矩阵和1x3矩阵之间进行划分时遇到了一些问题。我使用的两个矩阵是alfaalfa2,它们具有下一个结构(我在最后一部分添加dput()版本):

alfa
         jul 10  ago 10  sep 10
jul 10 28101696       0       0
ago 10 26558692 2048291       0
sep 10 25234674 2026633 3043638

alfa2
        jul 10  ago 10  sep 10
jul 10 1420547 2048291 3043638

我想在alfaalfa2之间进行划分。然后我使用此代码alfa/alfa2,我收到此错误:

Error in alfa/alfa2 : non-conformable arrays

通过这种划分,我想得到一个像这样的新矩阵:

         jul 10  ago 10  sep 10
jul 10 19.78230       0       0
ago 10 18.69610       1       0
sep 10 17.76405 0.98942       1

alfa的每一列除以alfa2的对应列。 dput()alfaalfa2是下一个:

alfa
structure(c(28101696.45, 26558692.38, 25234673.68, 0, 2048291.06, 
2026632.72, 0, 0, 3043637.6), .Dim = c(3L, 3L), .Dimnames = list(
    c("jul 10", "ago 10", "sep 10"), c("jul 10", "ago 10", "sep 10"
    )))

alfa2
structure(c(1420547.36, 2048291.06, 3043637.6), .Dim = c(1L, 
3L), .Dimnames = list("jul 10", c("jul 10", "ago 10", "sep 10"
)))

感谢您的帮助。

3 个答案:

答案 0 :(得分:4)

您可以使用sweep执行此任务

sweep(alfa, MARGIN = 2, STATS = alfa2, FUN = "/")
##        jul 10  ago 10 sep 10
## jul 10 19.782 0.00000      0
## ago 10 18.696 1.00000      0
## sep 10 17.764 0.98943      1

答案 1 :(得分:0)

您可以使用apply按行划分,但最后需要t转发。

t(apply(alfa,1,"/",alfa2))
           [,1]      [,2] [,3]
jul 10 19.78230 0.0000000    0
ago 10 18.69610 1.0000000    0
sep 10 17.76405 0.9894261    1

答案 2 :(得分:0)

t(t(alfa) / drop(alfa2))
#         jul 10    ago 10 sep 10
#jul 10 19.78230 0.0000000      0
#ago 10 18.69610 1.0000000      0
#sep 10 17.76405 0.9894261      1

基准:

library(microbenchmark)
microbenchmark(
t(t(alfa) / drop(alfa2)),
sweep(alfa, MARGIN = 2, STATS = alfa2, FUN = "/"),
t(apply(alfa,1,"/",alfa2))
)

# Unit: microseconds
#                                              expr    min      lq  median      uq     max neval
# t(t(alfa)/drop(alfa2))                            17.247 19.4030 20.9430 22.4830  97.934   100
# sweep(alfa, MARGIN = 2, STATS = alfa2, FUN = "/") 42.500 44.9640 45.8880 47.5820 227.282   100
# t(apply(alfa, 1, "/", alfa2))                     76.069 78.9945 80.3805 83.4605 177.390   100

set.seed(42)
alfa <- matrix(rnorm(1000), ncol=10)
alfa2 <- matrix(rnorm(10), ncol=10)

microbenchmark(
  t(t(alfa) / drop(alfa2)),
  sweep(alfa, MARGIN = 2, STATS = alfa2, FUN = "/"),
  t(apply(alfa,1,"/",alfa2))
)

# Unit: microseconds
#                                              expr     min       lq   median      uq      max neval
#                            t(t(alfa)/drop(alfa2))  25.870  27.7180  30.4895  31.722 1191.838   100
# sweep(alfa, MARGIN = 2, STATS = alfa2, FUN = "/")  60.362  64.2125  68.8320  73.913  164.456   100
#                     t(apply(alfa, 1, "/", alfa2)) 288.259 311.9730 326.4470 383.267 1912.176   100