Here's an example:
library(ggplot2)
library(scales) # for percent() function
custom_percent <- function(n){
function(x){
return(paste(percent(x), sprintf('(%d)', round(x* (n)))))
}
}
mydata = data.frame(x = rep(c('a','b','c'), each=100))
ggplot(mydata) + geom_text(aes_(x=~x, y=~..prop..,
label=bquote(.(custom_percent)(length(x))(..prop..)),
stat='count')
The function works properly outside of such an environment, but in order to use it with ggplot
, it has to be quoted in one way or another.
Unfortunately, I can't figure out how to properly return a generated function that contains a variable that is passed in such a manner. I've tried this:
custom_percent <- function(n){
n = enquo(n)
function(x){
return(paste(percent(x), sprintf('(%d)', round(x* (!!n)))))
}
}
But I get an error when I do this: Error in !n : invalid argument type
Does anyone know how to properly use the desired value of n
in the function returned by custom_percent()
?
And before anyone asks, I know I can generate the statistics in a summary data frame beforehand or use utils::getAnywhere()
as a workaround, but that's not the point of the question.