Create function whose arguments are formulas

Hi. I want to create a function whose arguments are formulas.

plotz <- function(y,z){
x<- seq(from=-5, to=5, by=.001)
plot(x,y, col="red")
points(x,z, col="blue")
}

f <- exp(x)
g <- exp(x^2)

plotz(f, g)

Not only does this not work, but I get error message that x is not found, presumably at f <- exp(x). How do I fix this? Thank you.

Error: object 'x' not found
Execution halted

x is not defined outside your function, so hence the error message.

You can learn how to deal with passing functions as arguments here:
Functionals ยท Advanced R. (had.co.nz)

The following seems to work:

plotz <- function(y, z, x_vals) {
plot(x_vals, eval(y, envir = list(x = x_vals)), col = "red", type = "l")
points(x_vals, eval(z, envir = list(x = x_vals)), col = "blue")
}

x <- seq(from = -5, to = 5, by = 0.001)
f <- expression(exp(x))
g <- expression(exp(x^2))

plotz(f, g, x)

x was in the .Local environment of plotz() before but here it it is in the .Global environment and that's why the original didn't work while this one does.

Here are two simpler alternatives

# no parameters
plotz <- function() {
  x = seq(from = -5, to = 5, by = .001)
  plot(x, exp(x), col = "orange")
  points(x, exp(x^2), col = "green")
}

plotz()


# parameterize everything

plotz <- function(begin, finish, incr, col1, col2) {
  x = seq(from = begin, to = finish, by = incr)
  plot(x, exp(x), col = col1)
  points(x, exp(x^2), col = col2)
}

plotz(begin = -4,finish =4,incr = .01,col1 = "pink",col2 = "steelblue")

Created on 2023-08-09 with reprex v2.0.2

perhaps one option is to leverage r formulas which are recognisable by their tilde notation i.e. ~ ; this is because you can write them, and they are unevaluated expressions until they are used in some way.
this might look like



myplot <- function(form_1,
                   form_2,
                   x_vals){
  l <- list(x=x_vals)
  plot(form_1,l,col="red")
  points(form_2,l,col="blue")
}
 
myplot(exp(x)~x,
       exp(x^2)~x,
       seq(from = -4, to = 4, by = .01))

image

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.