Why doesn't outer work the way I think it should (in R)?

后端 未结 1 688
天涯浪人
天涯浪人 2020-11-30 08:49

Prompted by @hadley\'s article on functionals referenced in an answer today, I decided to revisit a persistent puzzle about how the outer function works (or doe

相关标签:
1条回答
  • 2020-11-30 09:15

    outer(0:5, 0:6, sum) don't work because sum is not "vectorized" (in the sense of returning a vector of the same length as its two arguments). This example should explain the difference:

     sum(1:2,2:3)
      8
     1:2 + 2:3
     [1] 3 5
    

    You can vectorize sum using mapply for example:

    identical(outer(0:5, 0:6, function(x,y)mapply(sum,x,y)),
              outer(0:5, 0:6,'+'))
    TRUE
    

    PS: Generally before using outer I use browser to create my function in the debug mode:

    outer(0:2, 1:3, function(x,y)browser())
    Called from: FUN(X, Y, ...)
    Browse[1]> x
    [1] 0 1 2 0 1 2 0 1 2
    Browse[1]> y
    [1] 1 1 1 2 2 2 3 3 3
    Browse[1]> sum(x,y)
    [1] 27          ## this give an error 
    Browse[1]> x+y  
    [1] 1 2 3 2 3 4 3 4 5 ## this is vectorized
    
    0 讨论(0)
提交回复
热议问题