I installed mosaic package available in R to calculate derivative by typing install.packages('mosaic'). I created a function using makeFun and then i tried to calculate derivative in the following way
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. No need to install additional packages like mosaic
.
D
will give the derivative of expression, so using expression()
function, we create an expression and pass it to the D
function.
Then eval
will evaluate the expression and substitute
will substitute values of a
and b
in the expression.
get the derivative for an expression with respect to 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.
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. 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.