我有以下code片段,它合并了两个数据帧:
prim <- data.frame("t"=2007:2012,
"a"=1:6,
"b"=7:12)
secnd <- data.frame("t"=2012:2013,
"a"=c(5, 7))
final_df <- prim %>% full_join(secnd, by = 't') %>%
mutate(a = coalesce(as.integer(a.y),a.x)) %>%
select(t,a,b)
是否可以使用变量名而不是像上面那样对a
进行硬编码?也就是说,能否使以下无效代码正常工作?
var <- "a"
final_df <- prim %>% full_join(secnd, by = 't') %>%
mutate(var = coalesce(as.integer(var.y),var.x)) %>%
select(t,var,b)
答案 0 :(得分:2)
一种选择是使用syms
转换为符号并求值(!!!
)
library(tidyverse)
var <- "a"
prim %>%
full_join(secnd, by = "t") %>%
mutate_at(vars(starts_with(var)), as.integer) %>%
transmute(t, !! var := coalesce(!!! rlang::syms(paste0(var, c(".y", ".x")))), b)
# t a b
#1 2007 1 7
#2 2008 2 8
#3 2009 3 9
#4 2010 4 10
#5 2011 5 11
#6 2012 5 12
#7 2013 7 NA
答案 1 :(得分:1)
我们可以使用:=
赋值运算符在左侧进行标准评估:
library(dplyr)
library(rlang)
var <- "a"
final_df <- prim %>% full_join(secnd, by = 't') %>%
mutate(!!var := coalesce(as.integer(!!sym(paste0(var, ".y"))),!!sym(paste0(var, ".x")))) %>%
select(t,var,b)