作为函数的一部分,我正在尝试创建一个数据帧,我想以变量命名其中一列。下面是一些虚拟数据,是我坚持的部分。
library(tidyverse)
graph <- data.frame(brand = rep(c("A","B","C"), each = 3),
week_commencing = rep(as.Date(c('2020-03-01', '2020-04-01', '2020-05-01')), times = 3),
sessions = sample(1000:2000,9),
conv_rate = runif(9,0,1))
website = "A"
metric = "sessions"
graph %>%
filter(brand == (!!website)) %>%
group_by(brand) %>%
summarise(metric = max(get(metric)),
week_commencing = min(week_commencing),
lab = "This Year")
在总结函数调用中,我希望将列名指标称为会话,我尝试使用 get(metric( 和 (!!度量(作为列命名的一部分,但它不起作用。
这甚至可以在 R 中做到吗?任何帮助将不胜感激。
如果您希望在dplyr
函数的左侧使用变量作为名称(而无需单独重命名列(,则可以使用!!variable :=
而不是variable =
,因此在您的情况下,它将是:
graph %>%
filter(brand == (!!website)) %>%
group_by(brand) %>%
summarise(!!metric := max(get(metric)),
week_commencing = min(week_commencing),
lab = "This Year")
#> # A tibble: 1 x 4
#> brand sessions week_commencing lab
#> <chr> <int> <date> <chr>
#> 1 A 1901 2020-03-01 This Year
你的意思是这样吗?
library(tidyverse)
graph <- data.frame(brand = rep(c("A","B","C"), each = 3),
week_commencing = rep(as.Date(c('2020-03-01', '2020-04-01', '2020-05-01')), times = 3),
sessions = sample(1000:2000,9),
conv_rate = runif(9,0,1))
website = "A"
metric = "sessions"
graph %>%
filter(brand == (!!website)) %>%
group_by(brand) %>%
summarise(metric = max(get(metric)),
week_commencing = min(week_commencing),
lab = "This Year") %>% rename(sessions=metric)
# A tibble: 1 x 4
brand sessions week_commencing lab
<fct> <int> <date> <chr>
1 A 1819 2020-03-01 This Year
我们也可以用
library(dplyr)
graph %>%
filter(brand == website) %>%
group_by(brand) %>%
summarise(metric = max(!! rlang::sym(metric)),
week_commencing = min(week_commencing),
lab = "This Year") %>% rename_at(vars(metric), ~ 'sessions')
# A tibble: 1 x 4
brand sessions week_commencing lab
<chr> <int> <date> <chr>
1 A 1555 2020-03-01 This Year