gpt4 book ai didi

r - 如何控制 R 中旋转(更宽)列的顺序? tidyverse 问题 839

转载 作者:行者123 更新时间:2023-12-05 00:44:51 25 4
gpt4 key购买 nike

如果要旋转的值包含在多于一列中,我可以以更广泛的格式旋转数据。

us_rent_income %>%
pivot_wider(
names_from = variable,
names_glue = "{variable}_{.value}",
values_from = c(estimate, moe)
)

# A tibble: 52 x 6
GEOID NAME income_estimate rent_estimate income_moe rent_moe
<chr> <chr> <dbl> <dbl> <dbl> <dbl>
1 01 Alabama 24476 747 136 3
2 02 Alaska 32940 1200 508 13
3 04 Arizona 27517 972 148 4
4 05 Arkansas 23789 709 165 5
5 06 California 29454 1358 109 3
6 08 Colorado 32401 1125 109 5
7 09 Connecticut 35326 1123 195 5
8 10 Delaware 31560 1076 247 10
9 11 District of Columbia 43198 1424 681 17
10 12 Florida 25952 1077 70 3
# ... with 42 more rows

在此代码输出中,我希望列的顺序为 income_estimateincome_moerent_estimaterent_moe。设置 names_sort = T 没有帮助。更改 names_glue 中的顺序也无济于事。我知道我可以通过 select 和其他函数对列重新排序,但我只想知道 pivot_wider 中是否有任何参数可以这样做?

EDIT 问题似乎已经在开发中;已经讨论过herehere至少。

最佳答案

随着 tidyr 1.2.0 的出现,现在使用参数 names_vary

变得 super 简单
library(tidyr)
us_rent_income %>%
pivot_wider(
names_from = variable,
names_glue = "{variable}_{.value}",
values_from = c(estimate, moe),
names_vary = 'slowest'
)
#> # A tibble: 52 x 6
#> GEOID NAME income_estimate income_moe rent_estimate rent_moe
#> <chr> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 01 Alabama 24476 136 747 3
#> 2 02 Alaska 32940 508 1200 13
#> 3 04 Arizona 27517 148 972 4
#> 4 05 Arkansas 23789 165 709 5
#> 5 06 California 29454 109 1358 3
#> 6 08 Colorado 32401 109 1125 5
#> 7 09 Connecticut 35326 195 1123 5
#> 8 10 Delaware 31560 247 1076 10
#> 9 11 District of Columbia 43198 681 1424 17
#> 10 12 Florida 25952 70 1077 3
#> # ... with 42 more rows

reprex package 创建于 2022-02-17 (v2.0.1)

关于r - 如何控制 R 中旋转(更宽)列的顺序? tidyverse 问题 839,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65467620/

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