【问题标题】:Difference between mutate and mutate_mutate和mutate_之间的区别
【发布时间】:2018-06-18 18:22:49
【问题描述】:

我正在通过这篇文章学习如何处理不平衡的数据: https://www.r-bloggers.com/dealing-with-unbalanced-data-in-machine-learning/

而 Mutate 是一种用“dplyr”中的新值替换原始 NA 值的简单方法。

这里的代码出错了:

    models <- list(original = model_rf,
                       under = model_rf_under,
                       over = model_rf_over,
                       smote = model_rf_smote,
                       rose = model_rf_rose)
    comparison <- data.frame(model = names(models),
                         Sensitivity = rep(NA, length(models)),
                         Specificity = rep(NA, length(models)),
                         Precision = rep(NA, length(models)),
                         Recall = rep(NA, length(models)),
                         F1 = rep(NA, length(models)))

    for (name in names(models)) {
  model <- get(paste0("cm_", name))

  comparison[comparison$model == name, ] <- filter(comparison, model == name) %>%
    mutate(Sensitivity = model$byClass["Sensitivity"],
           Specificity = model$byClass["Specificity"],
           Precision = model$byClass["Precision"],
           Recall = model$byClass["Recall"],
           F1 = model$byClass["F1"])
}

但是,当我运行它时,我总是得到错误:$ 运算符对原子向量无效。 我仔细检查了代码,发现问题可能来自函数“mutate”。我尝试使用 mutate_ 有效。

但我不知道它为什么有效。我很想知道 mutate() 和 mutate_() 之间的区别谢谢!

【问题讨论】:

  • programming with dplyr vignettemutate_ 是 mutate 的标准评估版本,但它已被弃用,您应该使用 enquo!! 更可靠地获得您想要的结果。
  • 寻求帮助时,您应该包含一个简单的reproducible example,其中包含可用于测试和验证可能解决方案的示例输入和所需输出。

标签: r dplyr


【解决方案1】:

我无法对此进行测试,因为我没有任何数据,因此可能存在一些错误。但是,你应该试试这个:

library(dplyr)
get_results <- function(name) {
  model <- sym(paste0("cm_", name))

  list(data.frame(
    Sensitivity = !!model$byClass["Sensitivity"],
    Specificity = !!model$byClass["Specificity"],
    Precision = !!model$byClass["Precision"],
    Recall = !!model$byClass["Recall"],
    F1 = !!model$byClass["F1"]
  ))
}

comparison <- comparison %>%
  group_by(model) %>%
  mutate(temp_obj = get_results(model))) %>%
  unnest()

这完全取代了 for 循环。

【讨论】:

    猜你喜欢
    • 2019-04-15
    • 2015-05-02
    • 1970-01-01
    • 2021-12-25
    • 2020-05-10
    • 2014-09-20
    • 2010-10-28
    • 2015-10-04
    • 2012-08-12
    相关资源
    最近更新 更多