[英]calculating derivative in R using D function in mosaic package
I installed mosaic package available in R to calculate derivative by typing install.packages('mosaic').我安装了 R 中可用的马赛克包,通过键入 install.packages('mosaic') 来计算导数。 I created a function using makeFun and then i tried to calculate derivative in the following way
我使用 makeFun 创建了一个函数,然后我尝试按以下方式计算导数
y1 <- makeFun(a +b *x ~x, a=2, b=2)
dy1.dx <- D(a + b* x ~ x, a=2, b=2)
dy1.dx
but the console shows但控制台显示
" dy1.dx <- D(a+b*x~x, a=2, b=2)
Error in D(a + b * x ~ x, a = 2, b = 2) : unused arguments (a = 2, b = 2)"
How can I correct it?我该如何纠正?
using the base R's stats
package.使用基本 R 的
stats
包。 No need to install additional packages like mosaic
.无需安装其他软件包,如
mosaic
。
D
will give the derivative of expression, so using expression()
function, we create an expression and pass it to the D
function. D
将给出表达式的导数,因此使用expression()
函数,我们创建一个表达式并将其传递给D
函数。
Then eval
will evaluate the expression and substitute
will substitute values of a
and b
in the expression.然后
eval
将评估表达式,而substitute
将替换表达式中a
和b
值。
get the derivative for an expression with respect to x:得到表达式关于 x 的导数:
stats::D(expression(a + b * x), "x")
# b
evaluate the expression after substituting with values in the derivative.在用导数中的值替换后计算表达式。
b
is substituted with the value 2. b
被替换为值 2。
eval(substitute( stats::D(expression(a + b * x), "x"), list(a=2, b = 2) ))
# [1] 2
Another example:另一个例子:
stats::D(expression(a + a*b * x), "x")
# a * b
eval(substitute( D(expression(a + a*b * x), "x"), list(a=3, b = 2) ))
# 3 * 2
eval(eval(substitute( D(expression(a + a*b * x), "x"), list(a=3, b = 2) )))
# 6
D
used in your example is from library(mosaicCalc)
and not from base stat.您的示例中使用的
D
来自library(mosaicCalc)
而不是来自 base stat。 Install and call the library.安装并调用库。 Your function works normally.
您的功能正常工作。
require(mosaicCalc)
#> Loading required package: mosaicCalc
#> Warning: package 'mosaicCalc' was built under R version 3.6.3
#> Loading required package: mosaicCore
#> Warning: package 'mosaicCore' was built under R version 3.6.3
#> Registered S3 method overwritten by 'mosaic':
#> method from
#> fortify.SpatialPolygonsDataFrame ggplot2
#>
#> Attaching package: 'mosaicCalc'
#> The following object is masked from 'package:stats':
#>
#> D
dy1.dx <- D(a + b * x ~ x, a = 2, b = 2)
dy1.dx
#> function (x, a = 2, b = 2)
#> b
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.