在 dplyr::coalesce 中传递一个字符串作为变量名
Pass a string as variable name in dplyr::coalesce
我正在尝试创建一个新列,其中第一个 NA 值来自一组列,使用变量作为 dplyr::coalesce()
中的列名称。如何让它发挥作用?
我已经尝试将 coalesce() 与实际的列名一起使用并且它有效。当我传递一个变量时它失败了。
tb <- tibble(a = c("a", NA, "a", NA, "a"),
b = c(NA, "b", NA, NA, NA),
c = c('c', 'c', 'c', 'c', NA))
df <- tb %>%
mutate(combined = coalesce(a, b, c))
这适用于以下输出
# A tibble: 5 x 4
a b c combined
<chr> <chr> <chr> <chr>
1 a NA c a
2 NA b c b
3 a NA c a
4 NA NA c c
5 a NA NA a
但是,当我为列名创建变量时:
uCols <- c("a", "b", "c")
和运行类似的代码:
df <- tb %>%
mutate(combined = coalesce(uCols))
我收到以下错误:
Error: Column `combined` must be length 5 (the number of rows) or one, not 3
我试过使用 enexprs(uCols)
但那不起作用。
如何将 uCols
变量传递给 coalesce()
以便它按预期工作?
一个选项是将字符串转换为符号(syms
来自 rlang
),然后计算 (!!!
)
library(dplyr)
tb %>%
mutate(combined = coalesce(!!! rlang::syms(uCols)))
# A tibble: 5 x 4
# a b c combined
# <chr> <chr> <chr> <chr>
#1 a <NA> c a
#2 <NA> b c b
#3 a <NA> c a
#4 <NA> <NA> c c
#5 a <NA> <NA> a
或者另一种选择是 do.call
tb %>%
mutate(combined = select(., uCols) %>%
do.call(coalesce, .))
我正在尝试创建一个新列,其中第一个 NA 值来自一组列,使用变量作为 dplyr::coalesce()
中的列名称。如何让它发挥作用?
我已经尝试将 coalesce() 与实际的列名一起使用并且它有效。当我传递一个变量时它失败了。
tb <- tibble(a = c("a", NA, "a", NA, "a"),
b = c(NA, "b", NA, NA, NA),
c = c('c', 'c', 'c', 'c', NA))
df <- tb %>%
mutate(combined = coalesce(a, b, c))
这适用于以下输出
# A tibble: 5 x 4
a b c combined
<chr> <chr> <chr> <chr>
1 a NA c a
2 NA b c b
3 a NA c a
4 NA NA c c
5 a NA NA a
但是,当我为列名创建变量时:
uCols <- c("a", "b", "c")
和运行类似的代码:
df <- tb %>%
mutate(combined = coalesce(uCols))
我收到以下错误:
Error: Column `combined` must be length 5 (the number of rows) or one, not 3
我试过使用 enexprs(uCols)
但那不起作用。
如何将 uCols
变量传递给 coalesce()
以便它按预期工作?
一个选项是将字符串转换为符号(syms
来自 rlang
),然后计算 (!!!
)
library(dplyr)
tb %>%
mutate(combined = coalesce(!!! rlang::syms(uCols)))
# A tibble: 5 x 4
# a b c combined
# <chr> <chr> <chr> <chr>
#1 a <NA> c a
#2 <NA> b c b
#3 a <NA> c a
#4 <NA> <NA> c c
#5 a <NA> <NA> a
或者另一种选择是 do.call
tb %>%
mutate(combined = select(., uCols) %>%
do.call(coalesce, .))