Multiplying vector combinations

后端 未结 2 839
暗喜
暗喜 2020-12-11 06:36

Normal R vector multiplication, only multiplies vectors once, or recycles the shorter vector. IE:

> c(2,3,4) * c(1,2)
[1] 2 6 4
Warning message:
In c(2, 3         


        
相关标签:
2条回答
  • 2020-12-11 07:18

    You are probably looking for outer() or it's alias binary operator %o%:

    > c(2,3,4) %o% c(1,2)
         [,1] [,2]
    [1,]    2    4
    [2,]    3    6
    [3,]    4    8
    > outer(c(2,3,4), c(1,2))
         [,1] [,2]
    [1,]    2    4
    [2,]    3    6
    [3,]    4    8
    

    In your case, outer() offers the flexibility to specify a function that is applied to the combinations; %o% only applies the * multiplication function. For your example and data

    mph <- function(d, rpm) {
        cir <- pi * d
        cir * rpm / 63360 * 60
    }
    
    > outer(c(20,26,29), c(150,350), FUN = mph)
              [,1]     [,2]
    [1,]  8.924979 20.82495
    [2,] 11.602473 27.07244
    [3,] 12.941220 30.19618
    
    0 讨论(0)
  • 2020-12-11 07:35

    I believe the function you're looking for is outer

    > outer(cir, rpm, function(X, Y) X * Y / 63360 * 60)
              [,1]     [,2]
    [1,]  8.924979 20.82495
    [2,] 11.602473 27.07244
    [3,] 12.941220 30.19618
    

    In this case you could clean up the notation a bit:

    outer(cir, rpm / 63360 * 60)
    
    0 讨论(0)
提交回复
热议问题