mpettis mpettis - 1 year ago 86
R Question

Make parameterized function to return a function to eval

I'd like to parameterize a series of functions for the

plot creation to reduce redundancy. Below I have what it looks like (and works) without a parameterized function, and my attempt to do so.

I am trying to capture and pass on a parameter value to
in the function
, but I want to call
inline with the
function and return the
geom_vline() + geom_text()
as parameterized, so that they can get evaluated and do the same as what is being done in the first part.

I assume I need to understand quote/eval/substitute a bit better, but I don't at this point. Any help is appreciated as to how I would construct
be the equivalent of the
geom_vline() + geom_text()
calls, with parameters filled out.


## This works
## Making labeled vertical lines at 5 and 6
qplot(Sepal.Length, Sepal.Width, data=iris) +
geom_vline(xintercept=5, color="red", size=1) +
geom_text(x=5, y=4, label="5", hjust=0) +
geom_vline(xintercept=6, color="red", size=1) +
geom_text(x=6, y=4, label="6", hjust=0)

## I would like to parameterize these two statements
markvline <- function(e) {
geom_vline(xintercept=e, color="red", size=1) +
geom_text(x=e, y=4, label=as.character(e), hjust=0)}

## ... but this does not work
qplot(Sepal.Length, Sepal.Width, data=iris) +
markvline(5) +

Answer Source

The best I was able to do is:

markvline <- function(e) {
  list(geom_vline(xintercept=e, color="red", size=1),
       geom_text(x=e, y=4, label=as.character(e), hjust=0))}

qplot(Sepal.Length, Sepal.Width, data=iris) +
  markvline(5) + markvline(6)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download