Search code examples
rvectorizationcurve

R curve() on expression involving vector


I'd like to plot a function of x, where x is applied to a vector. Anyway, easiest to give a trivial example:

var <- c(1,2,3)
curve(mean(var)+x)
curve(mean(var+x))

While the first one works, the second one gives errors: 'expr' did not evaluate to an object of length 'n' and In var + x : longer object length is not a multiple of shorter object length

Basically I want to find the minimum of such a function: e.g.

optimize(function(x) mean(var+x), interval=c(0,1))

And then be able to visualise the result. While the optimize function works, I can't figure out how to get the curve() to work as well.. Thanks!


Solution

  • This can be done in the general case using sapply:

    curve(sapply(x, function(e) mean(var + e)))
    

    In the specific example you give, mean(var) + x, is of course arithmetically equivalent to what you're looking for. Similar shortcuts might exist for whatever more complicated function you're working with.