在 R 中按学期排序日期

Sorting dates by semesters in R

我想对 tibble 对象中的列进行排序(和重新排列)。我正在使用的 table(我们称它为 dataSet)如下所示:

Fall 2019 Fall 2020 Spring 2019 Spring 2020 Spring 2021
1 36 32 43 25
15 84 94 64 65

我想按以下顺序排序。

Spring 2019 Fall 2019 Spring 2020 Fall 2020 Spring 2021
32 1 43 36 25
94 15 64 84 65

由于列是本质上 字符串,我尝试使用str_sort(names(dataSet))。但是,此 returns 原始列名称 排序。如果我可以对列的名称进行排序,我知道我可以重新排列 tibble 对象中的列。我以前使用过时间对象,但这些通常用于 mm/dd/yyyy 等格式,但在学期方面没有。任何帮助将不胜感激。提前致谢!

这适用于所提供的数据,但季节顺序可能会因我们所处的世界部分而异。

library(tidyverse)

df <- tibble(`Fall 2019` = c(1, 15), `Fall 2020` = c(36, 84), `Spring 2019` = c(32, 94), `Spring 2020` = c(43, 64), `Spring 2021` = c(25, 65))


names(df) %>% str_match('^(\D+) (\d+)') %>%
  as_tibble %>% 
  arrange(V3, desc(V2)) %>% `[`(, 1) %>% 
  pull %>% 
  {select_at(df, .)}
#> Warning: The `x` argument of `as_tibble.matrix()` must have unique column names if `.name_repair` is omitted as of tibble 2.0.0.
#> Using compatibility `.name_repair`.
#> This warning is displayed once every 8 hours.
#> Call `lifecycle::last_lifecycle_warnings()` to see where this warning was generated.
#> # A tibble: 2 × 5
#>   `Spring 2019` `Fall 2019` `Spring 2020` `Fall 2020` `Spring 2021`
#>           <dbl>       <dbl>         <dbl>       <dbl>         <dbl>
#> 1            32           1            43          36            25
#> 2            94          15            64          84            65

reprex package (v2.0.1)

于 2021-12-01 创建

此处使用 relocate 和索引。您也可以使用名称:

library(dplyr)

df %>% 
  relocate(3,1,4,2,5)
  Spring2019 Fall2019 Spring2020 Fall2020 Spring2021
1         32        1         43       36         25
2         94       15         64       84         65