For the first example, I'll change it slightly because labs() doesn't need to evaluate xvar within df, but aes() does.
library("ggplot2")
library("rlang")
df <- data.frame("Age" = c(21,15, 28, 27, 30), "x" = runif(5),
"y"=runif(5), "z" = runif(5))
f <- function (xvar) {
xsym <- ensym(xvar) #Convert the string into a symbol
ggplot(data = df, aes(x = {{xsym}}, y = y)) +
geom_point() +
labs(x = xvar)
}
f("Age")
In your second example, CrossTable needs the vectors x and y to be passed as arguments.
There's a couple of ways to do this. The first, in just base R, you can extract
a column from a data.frame by passing the column name as a string.
library(gmodels)
f1 <- function(mydf, xvar, yvar) {
x <- mydf[[xvar]]
y <- mydf[[yvar]]
CrossTable(x=x, y = y, digits = 3)
}
In a second rlang approach, you can extract the column from the data.frame
by evaluating the column name within the environment of the data.frame.
f2 <- function(mydf, xvar, yvar) {
xsym <- ensym(xvar)
ysym <- ensym(yvar)
x <- rlang::eval_tidy(xsym, data = mydf)
y <- rlang::eval_tidy(ysym, data = mydf)
CrossTable(x = x, y = y, digits = 3)
}
f1(mydf = df, xvar = "Age", yvar = "z")
f2(mydf = df, xvar = "Age", yvar = "z")
There's a tidy evaluation with rlang cheat sheet at RStudio Cheatsheets - RStudio
which I've found useful.