r语言 - 为什么不replace_na实际上使用dplyr和管道替换缺失的值?



我最近在清理数据时一直在努力使用replace_na()函数。我有两个互补的变量,我想使用一个变量(varname2)来为另一个变量(varname1)提供缺失的值。我一直在尝试以下方法:

df %>%
replace_na(varname = varname2)

在响应中,我一直得到错误:

Did you misspecify an argument?
Run `rlang::last_error()` to see where the error occurred.
> df <- df %>% 
+    replace_na(varname1= varname2)
Error: 1 components of `...` were not used.
We detected these problematic arguments:
* `varname1`

建议一个有效的方法来解决这个问题?

我在其他地方发现了一个博客回应,Hadley自己说他们想从replace_na()转向更接近SQL的命令coalesce()。溶液中同时含有across()coalesce()

下面是我在工作中所做的一个例子:

df %>%
mutate(across(varname1, coalesce, varname2))

这似乎奏效了。

最新更新