I made this derivative script and I wanted to plot the graph of the result of the derivative along with the function. But I am not able to make the graph in the multivariate case f(x,y), the result of the derivative is taken as a value and not as a function. See the example below:
DD7<-function(x,r,contador=1){
dy<- substitute(x)
if(contador<1) {
stop("Grau de derivada menor que 1")
}
if(contador==1) {
der<-D(dy,c(r))
print(der)
x<- y <- seq(-3,3,length=50)
z<- outer(x,y,der)
persp(x,y,z)
}
else {
der2<- DD(D(dy,r),r,contador-1)
print(der2)
x2<- y2 <- seq(-3,3,length=50)
z2<- outer(x,y,der2)
persp(x,y,z2)
}
}
DD7(x*y^2,"y",1)
Error in get(as.character(FUN), mode = "function", envir = envir) :
object 'der' of mode 'function' was not found
CodePudding user response:
As I said in my comments, outer
's third argument needs to be a function. If you use eval(der)
, you may infer (correctly) that it is evaluating the expression (y^2
in this example) based on the objects found in the calling environment (the function's environment, to be specific). Since x
and y
are both found, then eval(der)
uses those variables, and returns a vector of the appropriate length.
The purpose of outer
is to do an outer-join of the values, expanding into length(x)*length(y)
combinations. If you look at the function as it is called by outer
, its first argument is length(x)*length(y)
elements long, all from the original x
; the second argument is also that length, from the original y
. The order of the values are such that all values from x
are paired with all values of y
.
Given this what we need to do is have eval(der)
operate in that environment.
DD7 <- function(x, r, contador=1) {
# ...
z2 <- outer(x, y, function(x, y) eval(der))
persp(x, y, z2)
# ...
}
DD7(x*y^2, "y", 1)
# x * (2 * y)
In that example, it might be confusing which x
and y
are referenced when; it's straight-forward: inside the anon-function passed to outer
, we also name them the same names so that the eval
uated der
will find the relevant expanded values.