在编程中使用dplyr合并 [英] Use dplyr coalesce in programming

查看:107
本文介绍了在编程中使用dplyr合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用dplyr的编程魔术,它是0.7.0版的新功能,将 coalesce 分为两列。下面,列出了一些尝试。

I'd like to use dplyr's programming magic, new to version 0.7.0, to coalesce two columns together. Below, I've listed out a few of my attempts.

df <- data_frame(x = c(1, 2, NA), y = c(2, NA, 3))

# What I want to do:
mutate(df, y = coalesce(x, y))

# Here's the expected output:
#> # A tibble: 3 x 2
#>       x     y
#>   <dbl> <dbl>
#> 1     1     1
#> 2     2     2
#> 3    NA     3

我认为 fn1 可以工作,但会将 varname 视为右侧的字符。

I thought fn1 would work, but it's treating varname as character on the right-hand side.

fn1 <- function(varname) {
  mutate(df, UQ(varname) := coalesce(x, !!varname))
}
fn1("y")
# Error in mutate_impl(.data, dots) : 
#   Evaluation error: Argument 2 must be type double, not character. 

另一次尝试使用 enquo

fn2 <- function(varname) {
  varname <- enquo(varname)
  mutate(df, varname := coalesce(x, !!varname))
}
fn2("y")  # same error

也许我可以用 !!! 拼接? (破坏者:我不能。)

Maybe I can splice with !!! instead? (Spoiler: I can't.)

fn3 <- function(varname) {
  varnames <- c("x", varname)
  mutate(df, UQ(varname) := coalesce(!!! varnames))
}
fn3("y")
#> # A tibble: 3 x 2
#>       x     y
#>   <dbl> <chr>
#> 1     1     x
#> 2     2     x
#> 3    NA     x

fn4 <- function(varname) {
  varnames <- quo(c("x", varname))
  mutate(df, UQ(varname) := coalesce(!!! varnames))
}
fn4("y")
# Error in mutate_impl(.data, dots) : 
#   Column `y` must be length 3 (the number of rows) or one, not 2 


推荐答案

您需要为右侧的 varname 使用 !! sym

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

或使用 UQ

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

这篇关于在编程中使用dplyr合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆