[R] R version of MATLAB symbolic toolbox (variable substitution)

Jennifer Young Jennifer.Young at math.mcmaster.ca
Wed Oct 14 15:31:38 CEST 2009


I'm translating some MATLAB code into R and have not found a simple
equivalent of the function R = subs(S,old,new).

I have, for example, a matrix such as this

mx<- function(){
  matrix( c(0, f1, f2,
            s1, 0, 0,
            0, s2, 0), 3,3, byrow=T)
}

and a matrix of data
dat<-matrix(c(1,2,3,4,2,3,4,5),2,4, byrow=T,
             dimnames<-list(NULL, c("f1","f2","s1","s2")))

I want to do two things with this matrix that seem to require different
formats.

1. evaluate this matrix many times using data from a matrix (for
stochastic simulation).  In the function form above, I can use
attach(as.data.frame(dat))
and the correct variables are fed to mx, but I'd rather avoid using attach
if possible.

2. I also want to manipulate the matrix (i.e., take the derivative of each
element with respect to a certain parameter).
If I use
mx<-c(0, expression(f1), expression(f2)) etc then I can use
deriv(mx[2], c("f1","f2")) etc to take the derivatives.  BUT, I can't find
how to then evaluate this version (in one line) for a row of data in dat.

f1<-2
f2<-4
eval(mx)
gives the scalar 4 (the last element of mx) rather than the vector.

I haven't come up with a form for mx that achieves both goals, while the
symbolic toolbox can do each in one line of code.
Does a clone package exist? I didn't see anything useful in R's Matlab
package.
In lieu of such a package I'll settle for being able to evaluate a vector
of expressions.  Probably I'm missing simple syntax here.

Thanks in advance,
Jen Young




More information about the R-help mailing list