【问题标题】:Multiply permutations of two vectors in RR中两个向量的排列相乘
【发布时间】:2015-10-22 13:22:41
【问题描述】:

我有两个长度为 4 的向量,想要乘以向量的排列:

A=(a1,a2,a3,a4)
B=(b1,b2,b3,b4)

我想要:

a1*b1;a1*b2;a1*b3...a4*b4

作为具有已知顺序的列表或具有 row.names=A 和 colnames=B 的 data.frame

【问题讨论】:

    标签: r permutation vector-multiplication


    【解决方案1】:

    看看expand.gridouter

    combination <- expand.grid(A, B)
    combination$Result <- combination$A * combination$B
    outer(A, B, FUN = "*")
    

    【讨论】:

    • outerFUN的默认参数是"*",所以outer(A,B)就足够了。
    【解决方案2】:

    使用outer(A,B,'*') 将返回一个矩阵

    x<-c(1:4)
    y<-c(10:14)
    outer(x,y,'*')
    

    返回

         [,1] [,2] [,3] [,4] [,5]
    [1,]   10   11   12   13   14
    [2,]   20   22   24   26   28
    [3,]   30   33   36   39   42
    [4,]   40   44   48   52   56
    

    如果你想把结果放在一个列表中,你可以这样做

    z<-outer(x,y,'*')
    z.list<-as.list(t(z))
    

    head(z.list) 返回

    [[1]]
    [1] 10
    
    [[2]]
    [1] 11
    
    [[3]]
    [1] 12
    
    [[4]]
    [1] 13
    
    [[5]]
    [1] 14
    
    [[6]]
    [1] 20
    

    即 x1*y1, x1*y2, x1* y3, x1*y4, x2*y1 ,...(如果您想要 x1*y1, x2*y1, ... 将 t(z) 替换为 @987654328 @)

    【讨论】:

    • 为了我的目的,reshape2 包中的“melt”在 external(A,B) 命令之后做得很好
    • expand.gridmelt(outer())) 效率更高
    【解决方案3】:

    我们可以试试vapply:

    vapply(B, '*', A, FUN.VALUE=numeric(length(A)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多