Brian Fisher
Brian Fisher

Reputation: 1367

Plot function specified by variable in R

I would like to plot a function that is determined by the value of a variable in R.

m1 <- function(x) x^2 # define a function 

curve(m1, 0, 10) #works

base plot I would expect this to work as well, but I get an error

w<- "m1"
curve(get(w), 0, 10) 
# Error in curve(get(w), 0, 10) : 
#   'expr' must be a function, or a call or an expression containing 'x'

This is strange since get(w) should return the function specified by "w"

m1
# function(x) x^2
get("m1")
# function(x) x^2
identical(m1, get(w))
# [1] TRUE

Upvotes: 1

Views: 167

Answers (2)

Ron Jensen
Ron Jensen

Reputation: 652

curve needs a variable named x. You need to explicitly provide the function call, not just function to make this work:

m1 <- function(x) x^2 # define a function 
w<- "m1"    
curve(get(w)(x), 0, 10) # works

Upvotes: 1

d.b
d.b

Reputation: 32548

The behavior seems to be consistent with the documentation (from ?curve)

expr

The name of a function, or a call or an expression written as a function of x which will evaluate to an object of the same length as x.

You could wrap it in another function as a workaround

mycurve = function(x, from, to) {
    f = get(x)
    curve(f, from, to)
}

mycurve(w, 0, 10)

OR

mycurve = function(x, from, to, ...) {
    curve(x, from, to, ...)
}

mycurve(get(w), 0, 10, n = 10)

Upvotes: 2

Related Questions