【发布时间】:2021-01-17 02:13:29
【问题描述】:
我正在尝试编写一个函数,该函数接受一个数据帧,将一列从 chr 转换为 dbl,然后将一列加 1。我还想可选地将某些值替换为NA。否则,如果不使用相关参数,我希望函数跳过 NA 替换步骤。
数据
library(tibble)
library(dplyr)
library(magrittr)
df <-
tibble(id = 1:10, col_of_interest = 21:30) %>%
add_row(id = 11, col_of_interest = 999) %>%
mutate(across(col_of_interest, as.character))
df
## # A tibble: 11 x 2
## id col_of_interest
## <dbl> <chr>
## 1 1 21
## 2 2 22
## 3 3 23
## 4 4 24
## 5 5 25
## 6 6 26
## 7 7 27
## 8 8 28
## 9 9 29
## 10 10 30
## 11 11 999
编写函数
函数应该:
- 接收数据。
- 将
col_of_interest从chr转换为dbl。 - 将
999替换为 NA (但前提是我指定应将999替换为NA) - 将
1添加到col_of_interest
我的尝试
在编写函数时,我参考了两个资源:
- 使用
{{ var }}将数据变量传递到函数参数中,如 here 所述。 -
if的使用基于this answer。
add_one <- function(data, var, na_if_val = NULL) {
data %>%
mutate(across({{ var }}, as.numeric)) %>%
{if( is.null( {{ na_if_val }} )
) . # <--- the dot means: "return the preexisting dataframe"
else
na_if( {{ na_if_val }} )
} %>%
mutate(across({{ var }}, add, 1))
}
当我在 df 对象上测试该函数时,我得到一个错误。
add_one(data = df,
var = col_of_interest,
na_if_val = "999")
Error in check_length(y, x, fmt_args("y"), glue("same as{fmt_args(~x)}")) : argument "y" is missing, with no default
谷歌搜索这个错误产生了this page,说明:
但是请注意,na_if() 只能接受长度为 1 的参数。
但是,在 add_one 函数的管道中仅合并 na_if( {{ na_if_val }} ) 确实有效。条件评估与is.null 相结合会导致函数中断。我不明白为什么。
【问题讨论】: