gpt4 book ai didi

r - tidyr::pivot_wider() 重新排序按 `name_from` 分组的列名称

转载 作者:行者123 更新时间:2023-12-04 10:31:34 25 4
gpt4 key购买 nike

我想对按 names_from 而不是 values_from 分组的列重新排序,这是我的最小示例:

mtcars %>% 
tidyr::pivot_wider(names_from = gear, values_from = c(vs, am, carb))

输出:

    mpg   cyl  disp    hp  drat    wt  qsec  vs_4  vs_3  vs_5  am_4  am_3  am_5 carb_4 carb_3 carb_5
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 21 6 160 110 3.9 2.62 16.5 0 NA NA 1 NA NA 4 NA NA
2 21 6 160 110 3.9 2.88 17.0 0 NA NA 1 NA NA 4 NA NA
3 22.8 4 108 93 3.85 2.32 18.6 1 NA NA 1 NA NA 1 NA NA

这是我想要的输出:

   mpg   cyl  disp    hp  drat    wt  qsec  vs_4  am_4 carb_4  vs_3  am_3 carb_3  vs_5  am_5 carb_5
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 21 6 160 110 3.9 2.62 16.5 0 1 4 NA NA NA NA NA NA
2 21 6 160 110 3.9 2.88 17.0 0 1 4 NA NA NA NA NA NA

提前致谢!

最佳答案

据我所知,这不能用 pivot_wider 完成,必须在之后完成。

这是一个冗长的尝试,但它完成了工作:

library(tidyverse)
suffixes <- unique(mtcars$gear)

pivoted <- mtcars %>%
tidyr::pivot_wider(names_from = gear, values_from = c(vs, am, carb))

names_to_order <- map(suffixes, ~ names(pivoted)[grep(paste0("_", .x), names(pivoted))]) %>% unlist
names_id <- setdiff(names(pivoted), names_to_order)

pivoted %>%
select(names_id, names_to_order)
#> # A tibble: 32 x 16
#> mpg cyl disp hp drat wt qsec vs_4 am_4 carb_4 vs_3 am_3
#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 21 6 160 110 3.9 2.62 16.5 0 1 4 NA NA
#> 2 21 6 160 110 3.9 2.88 17.0 0 1 4 NA NA
#> 3 22.8 4 108 93 3.85 2.32 18.6 1 1 1 NA NA
#> 4 21.4 6 258 110 3.08 3.22 19.4 NA NA NA 1 0
#> 5 18.7 8 360 175 3.15 3.44 17.0 NA NA NA 0 0
#> 6 18.1 6 225 105 2.76 3.46 20.2 NA NA NA 1 0
#> 7 14.3 8 360 245 3.21 3.57 15.8 NA NA NA 0 0
#> 8 24.4 4 147. 62 3.69 3.19 20 1 0 2 NA NA
#> 9 22.8 4 141. 95 3.92 3.15 22.9 1 0 2 NA NA
#> 10 19.2 6 168. 123 3.92 3.44 18.3 1 0 4 NA NA
#> # ... with 22 more rows, and 4 more variables: carb_3 <dbl>, vs_5 <dbl>,
#> # am_5 <dbl>, carb_5 <dbl>

reprex package 创建于 2020-02-25 (v0.3.0)

关于r - tidyr::pivot_wider() 重新排序按 `name_from` 分组的列名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60399441/

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