gpt4 book ai didi

r - 在编程中使用 dplyr 合并

转载 作者:行者123 更新时间:2023-12-04 14:48:14 25 4
gpt4 key购买 nike

我想使用 dplyr 的 programming magic ,新版本 0.7.0,到 coalesce两列在一起。下面,我列出了我的一些尝试。

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作为右侧的字符。
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

也许我可以拼接 !!!反而? (剧透:我不能。)
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

最佳答案

您需要使用 !!symvarname在右侧

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))))
}

关于r - 在编程中使用 dplyr 合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45405456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com