ant ant - 2 months ago 15
R Question

How to write a facet_wrap (ggplot2) within a function

I have written a function to plot a bar graph. But when I get to facet wrap the '~' sign is making things difficult.

rf.funct <- function(dat, predictor, feature){
ggplot(get(dat), aes(get(predictor), N)) +
geom_bar(stat = 'identity') +
facet_wrap(get(~feature)) # this is where the problem is

I've tried the following:

facet_wrap((get(~feature))) # invalid first argument
facet_wrap(paste0("~ ", get(feature))) # object 'feature' not found

How do i make sure the '~' sign gets included with the function?


Let me know if this works:

rf.funct <- function(dat, predictor, feature) {
  ggplot(dat, aes_string(predictor, "N")) +
    geom_bar(stat = 'identity') +

You don't need to use get. You've passed the data frame into the function using the dat argument, so just feed dat to ggplot and it will have the data data from within its environment.

The predictor and feature arguments should be entered as strings. Then you can use aes_string to specify the aesthetics. facet_wrap can now take a character vector directly, without need of a formula (as pointed out by @WeihuangWong).