在mutate和合并中使用变量名 [英] Using variable name in mutate and coalesce
本文介绍了在mutate和合并中使用变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下一段代码,它合并了两个数据帧:
I have the following piece of code that merges two dataframes:
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)
是否可以使用变量名而不是hard-如上所述对 a
进行编码?即,是否可以使以下无效代码正常工作?
Is it possible to use a variable name instead of hard-coding a
as done above? I.e., is it possible to make the following non-functioning code work?
var <- "a"
final_df <- prim %>% full_join(secnd, by = 't') %>%
mutate(var = coalesce(as.integer(var.y),var.x)) %>%
select(t,var,b)
推荐答案
一种选择是用 syms
转换为符号并求值( !!!
)
One option would be to convert to symbol with syms
and evaluate (!!!
)
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
这篇关于在mutate和合并中使用变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文