在dplyr::coalesce中将字符串作为变量名传递

3

我试图使用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()中,使其按预期工作?

1个回答

1
一种选项是将字符串转换为符号(使用来自rlangsyms函数),然后进行求值(使用!!!)。
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, .))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接