HiDefender
HiDefender

Reputation: 2378

Pass an Object Through a Function

This question discusses the issue, but I need to pass the object through my function. For example:

foo <- function(data, col1, col2) {
  boxplot(
    formula = col1 ~ col2,
    data = data)
}

When I run this:

foo(data, col1, col2)

I get object 'col1' not found.

How do I pass col1 and col2 through?

Upvotes: 1

Views: 112

Answers (1)

akrun
akrun

Reputation: 887901

In base R, we could construct the formula from unquoted arguments by first converting to string with deparse/substitute and then use paste to create the formula

foo <- function(data, col1, col2) {
  col1 <- deparse(substitute(col1))
  col2 <- deparse(substitute(col2))
  boxplot(
     formula = as.formula(paste0(col1, "~", col2)),
        data = data)
  }

-test it with inbuilt dataset

foo(mtcars, mpg, cyl)

enter image description here


Or if we prefer to use tidyverse, use the curly-curly ({{..}}) operator for simultaneously convert to quosures (enquo) and evaluate (!!)

library(dplyr)
library(ggplot2)
foo2 <- function(data, col1, col2) {
     data %>%
       select({{col1}}, {{col2}}) %>% 
       mutate( {{col2}} := factor({{col2}})) %>%
       ggplot(aes(x = {{col2}}, y = {{col1}})) + 
           geom_boxplot()
           }
       
foo2(mtcars, mpg, cyl)

enter image description here

Upvotes: 1

Related Questions