如何在dplyr::mutate()的RHS上使用动态变量?

如何在dplyr::mutate()的RHS上使用动态变量?,r,dplyr,tidyverse,mutate,R,Dplyr,Tidyverse,Mutate,是否可以在dplyr::mutate()的RHS上使用动态变量 玩具示例: 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(

是否可以在
dplyr::mutate()
的RHS上使用动态变量

玩具示例:

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)

由于它是一个字符串,我们可以转换为
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
或者使用
map2

library(purrr)
map2_dfc(baseline, followup, ~ temp %>%
                              transmute(!! .y := !! rlang::sym(.x) * 5)) %>%
    bind_cols(temp, .)

还有其他选项,如
\u at
transmute\u at
mutate\u at
mutate/cross
可以将字符串作为列名

谢谢!我在想,
rlang
中的某些东西将是solution@Zian你的评论被打断了
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)

    }
library(purrr)
map2_dfc(baseline, followup, ~ temp %>%
                              transmute(!! .y := !! rlang::sym(.x) * 5)) %>%
    bind_cols(temp, .)