gpt4 book ai didi

r - 将变量传递给 tidyr::pivot_wider 的 names_glue 参数

转载 作者:行者123 更新时间:2023-12-03 21:46:01 25 4
gpt4 key购买 nike

以下是一些我们使用两个名称进行更广泛旋转的愚蠢数据:

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_yesyes_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)

Error: Column names car_binary, car_binary, and car_binary must not be duplicated.


据推测,它正在评估变量并将结果字符串(即“汽车”或“二进制”)传递给胶水函数。我玩过一些我通常会用于整洁评估的东西( !!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
Here is the commit that added the names_glue parameter to pivot_wider -- although I can't really figure out how to troubleshoot with this.

最佳答案

您可以使用 sprtinf/paste0构造字符串:

library(tidyr)
df %>%
pivot_wider(
id_cols = food,
names_from = c(var1, var2),
names_glue = sprintf('{%s}_{%s}', var2, var1),
values_from = fun)

# food yes_toyota no_subaru yes_mazda no_skoda
# <chr> <dbl> <dbl> <dbl> <dbl>
#1 banana 2 4 3 6
#2 cheese 2 4 2 3

关于r - 将变量传递给 tidyr::pivot_wider 的 names_glue 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64111558/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com