Search code examples
rrlang

error in evaluating user arguments using `rlang`


I am trying to write a function that displays results from Bartlett's test, but having trouble using rlang to evaluate the user arguments properly in a piped chain of operations and in a formula. What am I doing wrong and how can I get this to work?

library(tidyverse)

# function body
tryfn <- function(data, x, y) {
  # creating a dataframe (works)
  data <-
    dplyr::select(
      .data = data,
      !!rlang::enquo(x),
      !!rlang::enquo(y)
    )
  print(head(data))

  # convert the grouping variable to factor (doesn't work)
  data %<>%
    stats::na.omit(.) %>%
    dplyr::mutate_at(
      .tbl = .,
      .vars = !!rlang::enquo(x),
      .funs = ~base::droplevels(x = base::as.factor(x = .))
    )
  print(head(data))

  # running the test (doesn't work)
  bartlett <- stats::bartlett.test(
    formula = !!rlang::enquo(y) ~ !!rlang::enquo(x),
    data = data,
    na.action = na.omit
  )

  print(summary(bartlett))
}

# using the function
tryfn(
  data = mtcars,
  x = am,
  y = wt
)
#>                   am    wt
#> Mazda RX4          1 2.620
#> Mazda RX4 Wag      1 2.875
#> Datsun 710         1 2.320
#> Hornet 4 Drive     0 3.215
#> Hornet Sportabout  0 3.440
#> Valiant            0 3.460
#> Error in !rlang::enquo(x): invalid argument type

Created on 2018-10-07 by the reprex package (v0.2.1)


Solution

  • We could pass string objects into .var. So convert the quosure to quo_name and use that

    tryfn <- function(data, x, y) {
      # creating a dataframe (works)
      x <- enquo(x)
      y <- enquo(y)
      x1 <- quo_name(x)
      y1 <- quo_name(y)
      data <-
        dplyr::select(
          .data = data,
          !!x,
          !!y
        )
      print(head(data))
    
      fml <- formula(paste0(y1, " ~ ", x1))
    
    
      # convert the grouping variable to factor (doesn't work)
      data <- data %>%
        stats::na.omit(.) %>%
        dplyr::mutate_at(
          .var = x1,
          .funs = ~base::droplevels(x = base::as.factor(x = .x))
        )
        bartlett <- stats::bartlett.test(
           formula = fml,
           data = data,
           na.action = na.omit
         )
    
        bartlett    
    
    }
    

    -test

    # using the function
    out <- tryfn(
      data = mtcars,
      x = am,
      y = wt
    )
    
    out
    
    #   Bartlett test of homogeneity of variances
    
    #data:  wt by am
    #Bartlett's K-squared = 0.71483, df = 1, p-value = 0.3978