代码之家  ›  专栏  ›  技术社区  ›  Alex

公式整洁评价的一个简单例子

  •  3
  • Alex  · 技术社区  · 8 年前

    我试图从 rlang . 作为一个简短的示例,我想向数据框架添加一列预测。这是在 modelr 但是我想直接通过这个公式,这样我可以进行一些整洁的评估。

    我有以下功能

    add_predictions <- function(data, model_exp){
      enquo_model_exp <- enquo(model_exp)
      fit <- data %>% as_tibble()  %>% !!enquo_model_exp
      data[[preds]] <- stats::predict(fit, data)
    }
    

    上述功能具有以下步骤

    1. enquo 公式

    2. 用数据拟合模型,并用 !!

    3. 利用拟合模型对数据进行预测

    这个函数用法的一个例子是 跟随。

    cars %>% 
      as_tibble() %>% 
      add_predictions(lm(speed ~ dist, data = .))
    
    1 回复  |  直到 8 年前
        1
  •  3
  •   Aurèle    8 年前

    library(tidyverse)
    
    add_predictions <- function(.data, formula,
                                .fun = lm, col = pred) {
      col <- enquo(col)
      col <- quo_name(col)
      mod <- .fun(formula = formula, data = .data)
      mutate(.data, !! col := predict(mod))
    }
    
    cars %>% 
      add_predictions(speed ~ dist, col = speed_pred) 
    
    #    speed dist speed_pred
    # 1      4    2   8.615041
    # 2      4   10   9.939581
    # 3      7    4   8.946176
    # 4      7   22  11.926392
    # 5      8   16  10.932987
    # 6      9   10   9.939581
    # 7     10   18  11.264122
    # 8     10   26  12.588663
    # 9     10   34  13.913203
    # 10    11   17  11.098554
    # ...
    

    add_predictions_2 <- function(.data, model_exp, col = pred) {
      col <- enquo(col)
      col <- quo_name(col)
      model_exp <- enquo(model_exp)
      mod <- rlang::eval_tidy(model_exp, data = list(. = .data))
      mutate(.data, !! col := predict(mod))
    }
    
    cars %>% 
      as_tibble() %>% 
      add_predictions_2(lm(speed ~ dist, data = .))
    
    # # A tibble: 50 x 3
    #    speed  dist  pred
    #    <dbl> <dbl> <dbl>
    #  1     4     2  8.62
    #  2     4    10  9.94
    #  3     7     4  8.95
    #  4     7    22 11.9 
    #  5     8    16 10.9 
    #  6     9    10  9.94
    #  7    10    18 11.3 
    #  8    10    26 12.6 
    #  9    10    34 13.9 
    # 10    11    17 11.1 
    # # ... with 40 more rows