是否可以在RHS上使用动态变量dplyr::mutate()
?
玩具示例:
temp <- tibble(
bl = c(1,2,3,4,5),
fu = c(11,22,33,44,55)
)
bl_var = "bl"
replacement_var = "fu"
# I want a dynamic version of this:
temp %>%
mutate(bl = fu)
# Something like:
temp %>%
mutate(!!bl := !!fu)
在我的实际用例中,我在基线测量了很多变量,在后续阶段测量了另一组变量。我不想再花一点时间,但想用后续变量替换基线变量。
该变量具有一致的命名方案:
基线变量可能是:x_1,x_2,x_3,...
后续变量将为:x_fu_1,x_fu_2,x_fu_3,...
感谢@akrun提供的整洁解决方案。对于其他类似情况的人,我修改了他们的解决方案,以将更新的基准变量连接回原始数据:
map2_dfc(baseline, followup, ~ temp %>%
group_by_at(vars(!! row_id)) %>%
transmute(!! .y := !! rlang::sym(.x))) %>%
right_join(temp, by = row_id)
由于它是一个字符串,我们可以转换为sym
bol并求值(!!
)以获取对象的值
library(dplyr)
temp %>%
mutate(!!bl_var := !! rlang::sym(replacement_var))
# A tibble: 5 x 2
# bl fu
# <dbl> <dbl>
#1 11 11
#2 22 22
#3 33 33
#4 44 44
#5 55 55
如果我们有多个变量,请为每个变量创建一个向量,然后使用map
或for
循环执行此操作
library(stringr)
baseline <- str_c("x", 1:3, sep="_")
followup <- str_c("x_fu", 1:3, sep="_")
for(i in seq_along(baseline)) {
temp <- temp %>%
mutate(!! followup[i] := !! rlang::sym(baseline[i]) * 5)
}
或使用 map2
library(purrr)
map2_dfc(baseline, followup, ~ temp %>%
transmute(!! .y := !! rlang::sym(.x) * 5)) %>%
bind_cols(temp, .)
还有其他选项,例如_at
withtransmute_at
或mutate_at
ormutate/across
可以将字符串作为列名
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句