How to write facet_wrap (ggplot2) in a function

I wrote a function for plotting a histogram. But when I get to enveloping, the “~” sign complicates the job.

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 tried the following:

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

How can I make sure the "~" sign is included in the function?

+6
source share
1 answer

You do not need to use get . You passed the data frame to the function using the dat argument, so just feed the dat to ggplot and it will have the data data from 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 must be entered as strings. Then you can use aes_string to indicate aesthetics. facet_wrap can now take a character vector directly, without the need for a formula (as @WeihuangWong pointed out).

+6
source

Source: https://habr.com/ru/post/1012392/


All Articles