econometrics_things
econometrics_things

Reputation: 29

Returning an equation from a function

Can I return an equation from a function? For example,

testfn<-function(x)
{
  y=x+z
  return(y)
}
testfn(2)

I want y=2+z

Is there any other way?

Upvotes: 2

Views: 84

Answers (3)

Rui Barradas
Rui Barradas

Reputation: 76663

This doesn't answer the question, but if you want to return a function from a function, it would be something like the following.

testfn <- function(x){
    force(x)
    function(z) x + z
}

y <- testfn(2)
y(3)
#[1] 5

If you are not at all interested in this just say so and I'll delete this answer.

Upvotes: 0

Roland
Roland

Reputation: 132969

I suspect you are looking for substitute:

testfn <- function(x) {
  substitute(y <- x + z, environment())
}
z <- 1
e <- testfn(2)
#y <- 2 + z
eval(e)
y
#[1] 3

Upvotes: 3

Sai Prabhanjan Reddy
Sai Prabhanjan Reddy

Reputation: 536

Are you looking for this?

testfn<-function(x)
{
  y = paste0("y=",x,"+z")
  return(y)
}
testfn(2)

[1] "y=2+z"

Upvotes: 0

Related Questions