以下是我们使用两个名称更广泛地透视的一些愚蠢数据:
library(tidyr)
df <- data.frame(
food = c('banana','banana','banana','banana','cheese','cheese','cheese','cheese'),
binary = c(rep(c('yes','no'), 4)),
car = c('toyota','subaru','mazda','skoda','toyota','subaru','mazda','skoda'),
fun = c(2,4,3,6,2,4,2,3))
df %>%
pivot_wider(
id_cols = food,
names_from = c(car, binary),
values_from = fun)
如果我们想改变新变量名的格式,例如,从toyota_yes
to yes_toyota
,我们使用names_glue
参数:
df %>%
pivot_wider(
id_cols = food,
names_from = c(car, binary),
names_glue = "{binary}_{car}",
values_from = fun)
我面临的问题是找到将变量名传递给names_glue
参数的正确语法。将变量传递给 很容易names_from
,例如:
var1 <- 'car'
var2 <- 'binary'
df %>%
pivot_wider(
id_cols = food,
names_from = c(var1, var2),
values_from = fun)
但我们不能直接这样做names_glue
:
df %>%
pivot_wider(
id_cols = food,
names_from = c(var1, var2),
names_glue = "{var1}_{var2}",
values_from = fun)
错误:列名
car_binary
、car_binary
和car_binary
不得重复。
大概它正在评估变量并将结果字符串(即“汽车”或“二进制”)传递给胶水函数。我玩过一些我通常用于整洁评估的东西(!!sym(...)
等),但没有任何工作。所需的输出如下,使用names_glue
参数的变量:
# A tibble: 2 x 5
food yes_toyota no_subaru yes_mazda no_skoda
<fct> <dbl> <dbl> <dbl> <dbl>
1 banana 2 4 3 6
2 cheese 2 4 2 3