What is R's equivalent to subs(function, x, value) in Matlab for substituting a value?

I have a moment generating function, so I differentiate it and substitute 0 for the moment of X. I don't know how to do it in R, can you please enlighten me.

In Octave,

pkg load symbolic; #octave symbolic package which itself uses sympy
syms y, x; #declare x,y as symbols

mgf = y / (y - x); #mgf for an exponential variable

mgf1 = diff(mgf, x, 1); #1st derivative of mgf 

mgf1_0 = subs(mgf1, x, 0); #substituting 0 in mgf1 for E(X)

I understand R doesn't have built-in symbolic functionality but given what I am trying to do is simply differentiation and substitution, something frequently needed when dealing with pdf/mgf/functions of RVs and other series expansion, I would like to know how I can perform in R in a simple manner (so I can focus on what to calculate, not how).

mgf <- expression(y / (y-x));
mgf1 <- D(mgf, "x");
#no symbolic substitute for x? eval won't work as y remains a variable

You can use rSymPy? There might be other symbolic packages in R too.

Octave's package Symbolic uses Sympy, but its subs(function, x, value) isn't a sympy function, so not in RSymPy.

You want to do things like this perhaps ?


(dexpr <- D(expression(y/(y-x)),"x"))

#evaluate it at y =1 , x= 0 
eval(dexpr,envir = list(y=1,x=0))

# substute 1 for y 
(dexpr_y1 <- rlang::parse_expr(stringr::str_replace_all(deparse(dexpr),"y","1")))

#evaluate at x=2 and x=3

Your substitute is closest, but given it is a string replace, the formula doesn't simplify....

Then base R is insufficient for your needs. You'll need a package with some simplify functionality.

There's an example of what seems to be the required functionality.

sympy("B = A.subs(x,1.1)") # replace x by 1.1 (btw, SymPy objects are immutable)

Thanks. I tried it, couldn't get it to work...

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.