Use dplyr coalesce in programming

谁说我不能喝 提交于 2019-12-05 08:23:16

You need to use !!sym for varname on the right side

library(rlang)
fn1 <- function(varname) {
  mutate(df, !!varname := coalesce(x, !!sym(varname)))
}

fn1("y")

# A tibble: 3 x 2
#      x     y
#  <dbl> <dbl>
#1     1     1
#2     2     2
#3    NA     3

Or use UQ:

fn1 <- function(varname) {
    mutate(df, UQ(varname) := coalesce(x, UQ(sym(varname))))
}

The following two approaches will work.

library(dplyr)

# Define a function to apply coalesce
col_fun1 <- function(df, Cols){
  df2 <- df %>%
    mutate(y = coalesce(!!!as.list(df %>% select(UQ(Cols)))))
  return(df2)
}

# Test the function
col_fun1(df = df, Cols = c("x", "y"))
# A tibble: 3 x 2
      x     y
  <dbl> <dbl>
1     1     1
2     2     2
3    NA     3

Or Try this.

# Define a function to apply coalesce
col_fun2 <- function(df, Cols){
  df2 <- df %>%
    mutate(y = coalesce(!!!as.list(df[, Cols])))
  return(df2)
}

# Test the function
col_fun2(df = df, Cols = c("x", "y"))
# A tibble: 3 x 2
      x     y
  <dbl> <dbl>
1     1     1
2     2     2
3    NA     3
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!