我试图使用dplyr::coalesce()
函数创建一个新列,该列的值为一组列中第一个NA值,并使用变量来表示这些列的名称。如何让它起作用?
我尝试使用实际的列名来运行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()
中,使其按预期工作?