ant
ant

Reputation: 585

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?

Upvotes: 9

Views: 2092

Answers (2)

Tom Wagstaff
Tom Wagstaff

Reputation: 1708

I was having a similar problem and the answers & comments on here helped me fix it. However, this post is about 6 years old now, and I think the most modern solution would be along these lines:

rf.funct <- function(dat, predictor, feature){
  ggplot(dat, aes({{predictor}}, N)) +
    geom_bar(stat = 'identity') +
    facet_wrap(enquo(feature))
}

Upvotes: 3

eipi10
eipi10

Reputation: 93811

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 from within its environment.

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

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).

Upvotes: 11

Related Questions