我试图动态创建列的名称并在mutate
df
预测数月为&#34; p1&#34;,&#34; p2&#34; 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))
答案 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 - .))