R语言自定义含if逻辑的函数未按预期生成新列问题排查
问题排查与解决
问题原因
- 条件逻辑嵌套错误:第二个
if(is.null(Third))被嵌套在if(!is.null(Third))的代码块内部,当Third=NULL时,外层的判断不执行,内层的逻辑完全不会被触发,所以根本不会生成new列。 - 变量引用方式错误:在
mutate里直接用first/second这类参数名,tidyverse无法正确识别数据框中对应的列,需要用{{}}语法来传递列名变量。
修正后的函数代码
apple <- function(data = data, first, second, Third = NULL) { require(tidyverse) if (!is.null(Third)) { data <- data %>% mutate(new = {{first}} + {{second}} + {{Third}}) } else { data <- data %>% mutate(new = {{first}} - {{second}}) } return(data) }
测试验证
分别测试两种场景:
- 传入
Third参数时:
results_with_third <- apple(data = data, first = x1, second = x2, Third = x3) head(results_with_third$new)
- 不传入
Third(或设为NULL)时:
results_no_third <- apple(data = data, first = x1, second = x2, Third = NULL) head(results_no_third$new)
两种场景都会正确生成符合计算逻辑的new列。
内容的提问来源于stack exchange,提问作者Tube
相关产品推荐
相关产品推荐

