Tuesday, August 21, 2012

Symbolic Math - Differentiation in R


# While R is primarily used as a statistical language for numerical calculations it is often useful to be able to manipulate symbols so as to avoid approximation error.

# In addition to a vector language R also can handle a limitted symbolic language.

# In order to do this first you specify a symbolic "expression".

fx = expression(x^2, 'x')

D(fx , 'x')
# We can see that this expression yeilds 2*x

D(D(fx , 'x'),'x')
# This will take the second derivative 2

# Now let's try something a little more sophisticated
fx = expression(x^5-1/x+cos(x)^x, 'x')

D(fx , 'x')

# R can also handle multiple variables.

fxyz = expression((x*y)^5-1/x^z+cos(x)^x)

# deriv is a similar function to D except that it expands solutions out.  The results are a little more complicated to interpret.

deriv(fxyz , c('x', 'y', 'z'))

# Integration on the other hand is a bit more difficult.  It requires external packages.

2 comments:

  1. OK, that's what I was looking for. Though I'll admit, symbolic math is better if you use Sage, but we all love R :)

    ReplyDelete
  2. Oh Wow.... Very great symbolic math post you have shared. I just find this post on this very nice web blog page. I will share it with others. Thanks :)

    ReplyDelete