我想使用当前 dplyr(1.0.2)的代码,将以v
开头的列中的NA
替换为列x
中的值。
我能够处理一个列中的情况:
suppressMessages(library(dplyr))
df <- data.frame(v1 = c(NA, 1, 2), v2 = c(3, NA, 4), v3 = c(5, 6, NA), x = c(7, 8, 9))
df %>% mutate(v1 = coalesce(v1, x))
#> v1 v2 v3 x
#> 1 7 3 5 7
#> 2 1 NA 6 8
#> 3 2 4 NA 9
由 reprex package (v0.3.0) 创建于2020年11月03日。
但是我无法弄清如何使其跨多列工作。
以下是我尝试过但没有成功的一些方法:
suppressMessages(library(dplyr))
df <- data.frame(v1 = c(NA, 1, 2), v2 = c(3, NA, 4), v3 = c(5, 6, NA), x = c(7, 8, 9))
df %>% mutate(across(starts_with("v")), . = coalesce(., x))
#> Error in list2(...): object 'x' not found
此内容由reprex包(v0.3.0)于2020年11月03日创建。
suppressMessages(library(dplyr))
df <- data.frame(v1 = c(NA, 1, 2), v2 = c(3, NA, 4), v3 = c(5, 6, NA), x = c(7, 8, 9))
df %>% mutate(across(starts_with("v")), . = coalesce(., df$x))
#> Error: Can't combine `..1` <data.frame> and `..2` <double>.
这段内容是由 reprex包 (v0.3.0) 于2020年11月03日创建的
感谢您的帮助。
)
放错位置了——难怪我从来没能让across()
正常工作。你们有没有关于匿名函数中使用.
和.x
的想法? - jtr13