heh
heh

Reputation: 23

Partially evaluate an expression in R

Sorry. I have an expression: #x^p

I want to evaluate this for a given p.

p -> 0
# 1 

p -> 1
#x

p -> 2
#x^2

p -> 3
#x^3

p -> -1
#x^-1

If I type in:

p -> 1
eval(p)
#1

BUT

p -> 1
eval(x^p)

Gives the error: #Error in eval(x^p) : object 'x' not found

I want it to give: #x

For p -> 2 , I want to get: #x^2 For p -> 0 , I want to get: #1

Upvotes: 2

Views: 47

Answers (1)

AndS.
AndS.

Reputation: 8110

Based on the update to your post, I think you want something like this. Note, you will need to have the packages Ryacas and gsubfn installed.

#function
sub_fun <- function(exp, def){
  Ryacas::yac_symbol(gsubfn::gsubfn(".", def, exp))
}

#examples
sub_fun(exp = "x^p", def = list("p" = 0))
#> y: 1

sub_fun(exp = "x^p", def = list("p" = 1))
#> y: x

sub_fun(exp = "x^p", def = list("p" = 2))
#> y: x^2

sub_fun(exp = "x^p", def = list("p" = 2, "x" = 3))
#> y: 9

sub_fun(exp = "p*x^p-(p^x-p)", def = list("p" = 2))
#> y: 2*x^2-(2^x-2)

sub_fun(exp = "p*x^p-(p^x-p)", def = list("p" = 2, "x" = 3))
#> y: 12

Upvotes: 1

Related Questions