【问题标题】:Mutate not behaving as expected inside custom functions变异在自定义函数中的行为不符合预期
【发布时间】:2019-11-05 05:51:33
【问题描述】:

在 R 中使用 TidyVerse 系列的新手。试图在函数中使用 mutate 将变量的行分类为正数或负数。在我的函数调用之外工作正常,但在其中严格返回零。

当我不使用 mutate 时,能够使函数按预期工作,但我想了解我遇到的问题。我可以说问题是我正在为函数传递一个字符串。我已经搞砸了各种事情,比如 as.name()、quo() 和 UQ,但我并没有真正取得成功。不太了解如何在函数中最好地使用 Dplyr 动词 - 我应该恢复到更正常的语法吗?

find_if_maj <- function(var_name,curr_year,k_i) {

  if(var_name == "unemp_chg") {
    temp <- agg_econ %>% select(year,var_name) %>% # Subsetting to the desired variable
      filter((year <= curr_year) & (year >= (curr_year - k_i))) %>% # Subsetting to the desired range of years
      mutate(indicator = ifelse(var_name <= 0, 1, 0)) # Creating a dummy indicator based on if the value is negative or positive
    return(temp) # Just returning the tibble for bug checking

  }

}

find_if_maj("unemp_chg",1970,5) %>% mutate(outsidefunc = ifelse(unemp_chg <= 0, 1, 0)) # Running the function, displaying what result should be


我希望 mutate 创建的指标列根据输入的值填充 1 和 0。无论输入值如何,该函数创建的指标列都只返回 0,但我生成的用于正确检查的 outside_func 列返回正确的值。

【问题讨论】:

  • 嗨 @Ariel Polani 欢迎来到 SO。对我们来说,帮助您很重要,我们提供了一些数据,以使我们能够重现知情的行为。关于您的问题,由于我们还没有数据,建议您查看名为 case_when (dplyr.tidyverse.org/reference/case_when.html) 的 dplyr 函数。 case_when 比 if else 简单得多,并且涵盖了更大范围的可能性
  • 感谢您的建议。使用 clintwood 的 !!sym 似乎对我有用。我会确保包含一些关于未来问题的数据。

标签: r dplyr


【解决方案1】:

在您的函数内部var_name 是一个字符串,但您希望它是对您的列名的引用。试试这个

find_if_maj <- function(var_name,curr_year,k_i) {

  if(var_name == "unemp_chg") {
    temp <- agg_econ %>% select(year,var_name) %>% # Subsetting to the desired variable
      filter((year <= curr_year) & (year >= (curr_year - k_i))) %>% # Subsetting to the desired range of years
      mutate(indicator = ifelse(!!sym(var_name) <= 0, 1, 0)) # Creating a dummy indicator based on if the value is negative or positive
    return(temp) # Just returning the tibble for bug checking

  }
}

【讨论】:

  • 谢谢,这确实成功了。如果你不介意我问,那有什么意义!! sym 之前?我目前的理解是 sym("string") 将字符串转换为可以引用我的列名的符号。不知道为什么没有!!。
  • !! 运算符是一个不引用运算符,仅在整洁的评估中工作。你可以阅读它here。我很高兴能帮助你。请accept my answer.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-09
相关资源
最近更新 更多