r - 变异在自定义函数中的行为不符合预期
问题描述
在 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 列会返回正确的值。
解决方案
您的函数内部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
}
}
推荐阅读
- laravel - Laravel 可审计历史表 - SQL 历史或审计包的优缺点?
- r - RStudio 中的 View() 有效,但 R x64 中的 View() 无效?
- tsql - 将重叠的日期范围转换为日期范围的行
- postgresql - 选择查询运行缓慢
- json - 隐藏关系 laravel
- javascript - SAPUI5 日历单行样式
- python - 如何在 keras 中加载预训练的词嵌入并输出不同的类
- typescript - 如何从 Vuetify 数据表组件的类中获取数据?
- python - 如何到达 QTreeWidget 第二列 QComboBox 中的内容?
- pascal - 在 Pascal 中使用 MOD