试图将超过2个向量传递给R中的函数 [英] Trying to pass more than 2 vectors to a function in R

查看:115
本文介绍了试图将超过2个向量传递给R中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过a = -1:1 和 b = -1:1 e ^(ax + b) c $ c>用于 X 的各种值。我希望输出形式为5个元素的列表。列表中的每个元素都是3X3矩阵。

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 element in the list is 3X3 Matrix.

我使用Outer和Vectorize实现了这一点。

I did achieve this using Outer and Vectorize.

 sigm = function(a=0,b=0,x){
 return(exp(x*a+b))
 }

 sigm1 = Vectorize(function(a=-1:1,b=-1:1,x){

 outer(a,b,sigm,x)
 },SIMPLIFY = FALSE)

code> sigm1(x = 1:3)给出所需的输出

Now, sigm1(x=1:3) gives the required output

 [[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

这个代码片段的唯一缺点是我使用的默认值是 a = -1:1 b = - 1: 1 。当我在函数调用期间尝试通过它时,它会失灵。例如

The only draw back with this code snippet is I am using the default values of a=-1:1 and b=-1:1. When I try to pass the same during function calling, it goes haywire. E.g.

sigm1(-1:1,-1:1,1:3)

[[1]]
      [,1]
[1,] 0.1353353

[[2]]
 [,1]
[1,]    1

[[3]]
     [,1]
[1,] 54.59815

我无法弄清楚为什么传递参数会使输出产生差异。

I am unable to figure out why passing the arguments is making this difference in output.

推荐答案

在这种情况下,您只应该向量化变量 x

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)

然后运行 sigm1(-1:1,-1:1,1:3)会得到您想要的结果。

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

这篇关于试图将超过2个向量传递给R中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆