有没有办法创建一个将功能作为R中的输入值包含函数的矩阵?
例如,我需要写的东西的MATLAB代码看起来像这样
f = @(x) [ 100*x(1) - 4*x(1)*x(2);
-20*x(2) + 0.01*x(1)*x(2)];
J = @(x) [100-4*x(2), -4*x(1);
0.01*x(2), -20+0.01*x(1)];
。 在R中,我
rabbits <- function(x) { #defined a function
100*x(1) - 4*x(1)*x(2) }
foxes <- function(x) { #defined a second function
-20*x(2) + 0.01*x(1)*x(2)}
function_vector <- matrix(0, 2, 1) # created a 0 matrix to later append values
function_vector[1,1] <- function_vector[1,1] + rabbits #added values to 0 matrix
function_vector[2,1] <- function_vector[2,1] + foxes
显然尝试过,我无法将功能存储在矩阵中,因为它给了我一个错误“非数字参数到二进制运算符”。通常,我需要此矩阵来进行手动二维根系查找,因此,如果您知道其他任何方法来编码它(除了内置功能外),那么我也很感激:)
For example, the MATLAB code for something I need to write looks like this
f = @(x) [ 100*x(1) - 4*x(1)*x(2);
-20*x(2) + 0.01*x(1)*x(2)];
J = @(x) [100-4*x(2), -4*x(1);
0.01*x(2), -20+0.01*x(1)];
What would be an analog in R to store functions as matrix values?
In R, I tried
rabbits <- function(x) { #defined a function
100*x(1) - 4*x(1)*x(2) }
foxes <- function(x) { #defined a second function
-20*x(2) + 0.01*x(1)*x(2)}
function_vector <- matrix(0, 2, 1) # created a 0 matrix to later append values
function_vector[1,1] <- function_vector[1,1] + rabbits #added values to 0 matrix
function_vector[2,1] <- function_vector[2,1] + foxes
Apparently, I can't store functions in matrixes, as it gives me an error "non-numeric argument to binary operator". Generally, I need this matrix for manual two-dimensional root finding, so if you know any other way to code it (apart from inbuilt functions), then I would also appreciate that :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

您可以将函数存储在列表数组中。它是通过设置列表的
dim
属性来创建的。或者,您也可以将函数存储在数据框的列表变量中。我在这里使用 tibble,因为构造函数
data.frame()
由于某种原因不喜欢函数列表。但如果您愿意,可以将其强制为纯数据帧。请注意,我在这里使用了简写函数语法
\(...) ...
。如果您的 R 版本早于 4.1,则必须将其替换为function(...) {...}
。由 reprex 软件包 (v2.0.1) 创建于 2022 年 4 月 1 日
You can store functions in a list array. It is created by setting the
dim
attribute of a list.Alternatively, you can also store functions in list variables of data frames. I am using a tibble here, because the constructor
data.frame()
doesn't like lists of functions for some reason. But it is possible to coerce it to a plain data frame if you prefer.Note that I have used the shorthand function syntax
\(...) ...
here. If you have an R version older than 4.1 you will have to replace it withfunction(...) {...}
.Created on 2022-04-01 by the reprex package (v2.0.1)