首页 > 解决方案 > 变异在自定义函数中的行为不符合预期

问题描述

在 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 列会返回正确的值。

标签: rdplyr

解决方案


您的函数内部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

  }
}

推荐阅读