使用" dplyr :: mutate"

时间:2018-04-03 06:57:01

标签: r tidyverse

我试图动态创建列的名称并在mutate

中使用它
  1. 我的df预测数月为" p1"," p2"
  2. 我想计算实际的差异
  3. 我想提供的输入只是预测期间代码,例如:" p1"找出答案
  4. 示例df

    df <- data.frame(stringsAsFactors=FALSE,
              product = c("aa", "bb", "cc"),
          act_rev_mtd = c(100L, 110L, 120L),
         rev_fcast_p1 = c(100L, 100L, 100L),
         rev_fcast_p2 = c(110L, 110L, 110L)
      )
    
    reporting_mth <- "p1"
    

    这是我尝试过的,不起作用:

    df1 <- df %>%
      mutate(mtd_rev_var = act_rev_mtd - !!paste0("rev_fcast_", reporting_mth))
    

2 个答案:

答案 0 :(得分:2)

您可以使用get()代替!!,以便按名称搜索对象:

df1 <- df %>%
  mutate(mtd_rev_var = act_rev_mtd - get(paste0("rev_fcast_", reporting_mth)))

结果是:

df1
  product act_rev_mtd rev_fcast_p1 rev_fcast_p2 mtd_rev_var
1      aa         100          100          110           0
2      bb         110          100          110          10
3      cc         120          100          110          20

答案 1 :(得分:2)

我们可以使用sym中的rlang将其转换为符号,然后执行!!

df %>%
    mutate(mtd_rev_var = act_rev_mtd - !!rlang::sym(paste0("rev_fcast_", reporting_mth)))
#     product act_rev_mtd rev_fcast_p1 rev_fcast_p2 mtd_rev_var
#1      aa         100          100          110           0
#2      bb         110          100          110          10   
#3      cc         120          100          110          20

或者将其作为mutate_at

中的字符串传递
df %>%
   mutate_at(vars(paste0("rev_fcast_", reporting_mth)), funs(mtd_rev_var = act_rev_mtd - .))