代码之家  ›  专栏  ›  技术社区  ›  Indrajeet Patil

使用`rlang计算用户参数时出错`

  •  1
  • Indrajeet Patil  · 技术社区  · 6 年前

    rlang 在管道操作链和公式中正确计算用户参数。我做错了什么?我怎样才能让它工作?

    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
    

    创建日期:2018-10-07 reprex package

    1 回复  |  直到 6 年前
        1
  •  1
  •   akrun    6 年前

    我们可以将字符串对象传递到 .var . 所以把问题转化为 quo_name 用这个

    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    
    
    }
    

    -试验

    # 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