Trying to pass more than 2 vectors to a function in R

前端 未结 2 888
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-26 10:50

I want to compute e^(ax+b) over a=-1:1 and b=-1:1 for various values of X. I want the output in the form a list of 5 elements. Each elemen

相关标签:
2条回答
  • 2021-01-26 11:44

    We can just use lapply and don't need Vectorize at all:

    lapply(x, function(x) outer(a, b, sigm, x = x))
    

    giving:

    [[1]]
              [,1]      [,2]     [,3]
    [1,] 0.1353353 0.3678794 1.000000
    [2,] 0.3678794 1.0000000 2.718282
    [3,] 1.0000000 2.7182818 7.389056
    
    [[2]]
               [,1]      [,2]       [,3]
    [1,] 0.04978707 0.1353353  0.3678794
    [2,] 0.36787944 1.0000000  2.7182818
    [3,] 2.71828183 7.3890561 20.0855369
    
    [[3]]
               [,1]        [,2]       [,3]
    [1,] 0.01831564  0.04978707  0.1353353
    [2,] 0.36787944  1.00000000  2.7182818
    [3,] 7.38905610 20.08553692 54.5981500
    
    0 讨论(0)
  • 2021-01-26 11:47

    In this case, you should only vectorize the variable x.

    sigm1 = Vectorize(function(a=-1:1,b=-1:1,x){
                        outer(a,b,sigm,x)}, vectorize.args = "x" ,SIMPLIFY = FALSE)
    

    Then running sigm1(-1:1,-1:1,1:3) will gives the result you want.

    0 讨论(0)
提交回复
热议问题