I want to create a function that taking a data base, variable_1 y variable_2 builds a mosaic plot!
var_1<-rep(c("A","B","C","B","A","C"),10)
var_2<-c(rep(c("1","0"),10),rep("0",5),rep(c("0","1","0"),10),rep("1",5) )
dat<-data.frame(var_1,var_2)
The function takes 3 arguments as explained:
mosaic_fig<-function(db,var1,var2){
library(ggmosaic)
mosac <- ggplot2::ggplot(data = db) +
geom_mosaic(ggplot2::aes(x = product({{var2}}), fill = {{var1}})) +
ggplot2::labs(y="", x="", title = "")
return(mosac)
}
Now I try to use the function with the data I just provided and this happens:
windows()
mosaic_fig(dat,var_1,var_2)
Warning message:
Computation failed in `stat_mosaic()`
Caused by error in `[.data.frame`:
! undefined columns selected
It is clear I'm having problems with the quasiquotation in the product() function. I have used quasiquotation in other ggplot functions and it worked nicely... why not here?
You will need rlang::enexprs
instead of rlang::exprs
(which is called by ggmosaic::product
).
From help("topic-defuse")
:
You can defuse your own R expressions with expr(). (...) You can defuse the expressions supplied by the user of your function with the en-prefixed operators (...)
var_1 <- rep(c("A", "B", "C", "B", "A", "C"), 10)
var_2 <- c(rep(c("1", "0"), 10), rep("0", 5), rep(c("0", "1", "0"), 10), rep("1", 5))
dat <- data.frame(var_1, var_2)
## better not to require libraries within a function
library(ggmosaic)
#> Loading required package: ggplot2
mosaic_fig <- function(db, var1, var2) {
ggplot2::ggplot(data = db) +
ggmosaic::geom_mosaic(ggplot2::aes(x = rlang::enexprs(var2), fill = {{ var1 }})) +
ggplot2::labs(y = "", x = "", title = "")
}
mosaic_fig(dat, var_1, var_2)
#> Warning: `unite_()` was deprecated in tidyr 1.2.0.
#> ℹ Please use `unite()` instead.
#> ℹ The deprecated feature was likely used in the ggmosaic package.
#> Please report the issue at <https://github.com/haleyjeppson/ggmosaic>.
Created on 2023-04-10 with reprex v2.0.2