Search code examples
rderivative

multivariable derivative in R


Could somebody help me with simple mathematic operation in R?

All I want to do is:

I have a function

f <-(a1*x1+a2*x2+…+an*xn~x1&…&xn)

and derivative of this function

df<-D(f(x1…xn)~…)

What I need to fill in the '…' gap to obtain a result of multivariable derivative? The problem is that I can't address to value of vector c(x1,x2,x3…xn)

As a result I need to write a "for"-cycle on each step of which it gets me a result of derivative


Solution

  • Do you have a fixed n? If so, you can use parse to transform a string in an expression:

    x = c('x1','x2','x3')
    a = c('a1','a2','a3')
    expr=parse(text=paste(paste(x, a, sep="*"), collapse="+"))
    
    #> sapply(x, function(u) D(expr,u))
    #$x1
    #a1
    
    #$x2
    #a2
    
    #$x3
    #a3