Search code examples
rsymbolic-math

Evaluate a symbolic Ryacas expression


This is a reproducible example:

a <- 0.05
za.2 <- qnorm(1-a/2)
b <- 0.20
zb <- qnorm(1-b)

lambda12 <- -log(1/2)/12
lambda18 <- -log(1/2)/18
theta <- lambda18/lambda12
(d = round(4*(za.2+zb)^2/log(theta)^2))   

Tf<-36
library(Ryacas)
n <- Sym("n")

Solve(n/2*(2-exp(-lambda12*Tf)-exp(-lambda18*Tf))==d , n)

The last line returns

expression(list(n == 382/1.625))

Is there a way to extract the quotient and assign it to another variable (235.0769)?


Solution

  • G.Grothendieck pointed out in comments that you'll need to first to capture the expression to be operated upon below:

    soln <- Solve(n/2*(2-exp(-lambda12*Tf)-exp(-lambda18*Tf))==d , n) 
    X <- yacas(soln)$text
    

    Then, to extract the quotient, you can take advantage of the fact that many R language objects either are or can be coerced to lists.

     X <- expression(list(n == 382/1.625))
     res <- eval(X[[1]][[2]][[3]])
     res
     [1] 235.0769
    

    The following just shows why that sequence of indices extracts the right piece of the expression:

    as.list(X)
    # [[1]]
    # list(n == 382/1.625)
    
    as.list(X[[1]])
    # [[1]]
    # list
    # 
    # [[2]]
    # n == 382/1.625
    
    as.list(X[[1]][[2]])
    # [[1]]
    # `==`
    # 
    # [[2]]
    # n
    # 
    # [[3]]
    # 382/1.625