【问题标题】:Transform Date Dataframe转换日期数据框
【发布时间】:2021-02-23 15:46:23
【问题描述】:

我有一个看起来像这样的数据框:

County    2020-01-22  2020-01-23  2020-01-24
Autauga   0           1           0
Baldwin   0           2           4
Barbour   0           3           1

但是,我想重新格式化它,以便按县获得每天的计数。像这样的:

County   year  month  day  value 
Autauga  2020  01     22   0
Baldwin  2020  01     22   0
Barbour  2020  01     22   0
Autauga  2020  01     23   1
Baldwin  2020  01     23   2
Barbour  2020  01     23   3
Autauga  2020  01     24   0
Baldwin  2020  01     24   4
Barbour  2020  01     24   1

【问题讨论】:

    标签: r dataframe reformat


    【解决方案1】:

    我们可以只使用pivot_longer 并指定names_sep

    library(tidyr)
    pivot_longer(df1, cols = -County, 
         names_to = c("year", "month", "day"), names_sep = "-")
    

    -输出

    # A tibble: 9 x 5
    #  County  year  month day   value
    #  <chr>   <chr> <chr> <chr> <int>
    #1 Autauga 2020  01    22        0
    #2 Autauga 2020  01    23        1
    #3 Autauga 2020  01    24        0
    #4 Baldwin 2020  01    22        0
    #5 Baldwin 2020  01    23        2
    #6 Baldwin 2020  01    24        4
    #7 Barbour 2020  01    22        0
    #8 Barbour 2020  01    23        3
    #9 Barbour 2020  01    24        1
    

    数据

    df1 <- structure(list(County = c("Autauga", "Baldwin", "Barbour"), 
           `2020-01-22` = c(0L, 
    0L, 0L), `2020-01-23` = 1:3, `2020-01-24` = c(0L, 4L, 1L)), 
    class = "data.frame", row.names = c(NA, 
    -3L))
    

    【讨论】:

      【解决方案2】:

      这行得通吗:

      library(dplyr)
      library(tidyr)
      df %>% pivot_longer(!County, names_to = 'date') %>% 
      separate(date, into = c('year','month','day'), sep = '-') %>% arrange(day)
      # A tibble: 9 x 5
        County  year  month day   value
        <chr>   <chr> <chr> <chr> <dbl>
      1 Autauga 2020  01    22        0
      2 Baldwin 2020  01    22        0
      3 Barbour 2020  01    22        0
      4 Autauga 2020  01    23        1
      5 Baldwin 2020  01    23        2
      6 Barbour 2020  01    23        3
      7 Autauga 2020  01    24        0
      8 Baldwin 2020  01    24        4
      9 Barbour 2020  01    24        1
      

      【讨论】:

      • 这行得通,但是当我在完整数据集上使用它时,我收到以下警告消息:警告消息:预期 2 件。在 189588 行 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ... ].
      • 我认为将数据稍微总结一下,简单地列出县、年、月和值,实际上会更实用。我假设我需要做的就是删除日期规范并将安排()函数编辑为月份?
      • @JoseAlfaro,如果您不需要“day”,那么您可以直接放弃它,无需安排。我想它会按县安排。
      猜你喜欢
      • 2021-03-18
      • 2014-07-06
      • 1970-01-01
      • 2014-01-14
      • 1970-01-01
      • 2021-12-27
      • 2018-07-13
      • 2018-12-15
      相关资源
      最近更新 更多