How to detect if bare variable or string

Viewed 375

I am trying to write a plotting function where you can pass bare column names to select which columns are plotted. I would like also to be able to specify a string as the color.

I have found that I need to use shQuote if I want to pass a string to aes_string. Now my problem is to figure out if a bare name or a string was passed. How would I do this?

dat <- data.frame(
    time = factor(c("Lunch","Dinner"), levels=c("Lunch","Dinner")),
    total_bill = c(14.89, 17.23)
)



plot_it <- function(dat, x,y, fill){
    require(rlang)
    require(ggplot2)

    x <- enquo(x)
    y <- enquo(y)
    fill <- enquo(fill)

    xN <- quo_name(x)
    yN <- quo_name(y)
    fillN <- quo_name(fill)

ggplot(data=dat, aes_string(x=xN, y=yN, fill=fillN)) +
    geom_bar(stat="identity")

}

This works:

plot_it(dat, time, total_bill, time)

This does not:

plot_it(dat, time, total_bill, "grey")

Note that this requires the newest versions of rlang and ggplot2.

4 Answers
Related