mpettis mpettis - 1 month ago 16
R Question

Make parameterized function to return a function to eval

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

ggplot2
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
geom_vline()
and
geom_text()
in the function
markvline()
, but I want to call
markvline()
inline with the
qplot()
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
markvline()
be the equivalent of the
geom_vline() + geom_text()
calls, with parameters filled out.

library(ggplot2)

## 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) +
markvline(6)

Answer

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)