簡體   English   中英

R:按日期排序(按年份,按月)

[英]R: Order by Date (by Year, by Month)

我在第1列中的格式為mm / yyyy,然后在第2列中生成。

  1. 月結果
  2. 01/2018 96.13636
  3. 02/2018 96.40000
  4. 3/2018 94.00000
  5. 04/2018 97.92857
  6. 05/2018 95.75000
  7. 11/2017 98.66667
  8. 12/2017 97.78947

我如何按月訂購,以便從第一個月(11月1日)開始到結束(05/2018)。

我嘗試了幾個“訂單”,但似乎沒有一個按年訂購,然后按月訂購

在tidyverse(w / lubridate添加):

library(tidyverse)
library(lubridate)

dfYrMon <- 
    df1 %>% 
    mutate(date = parse_date_time(month, "my"),
           year = year(date),
           month = month(date)
           ) %>% 
    arrange(year, month) %>% 
    select(date, year, month, result)

有了數據:

df1 <- tibble(month = c("01/2018", "02/2018", "03/2018", "04/2018", "05/2018", "11/2017", "12/2017"), 
              result = c(96.13636, 96.4, 94, 97.92857, 95.75, 98.66667, 97.78947))

會得到這個'數據幀':

 # A tibble: 7 x 4 date year month result <dttm> <dbl> <dbl> <dbl> 1 2017-11-01 2017 11 98.66667 2 2017-12-01 2017 12 97.78947 3 2018-01-01 2018 1 96.13636 4 2018-02-01 2018 2 96.40000 5 2018-03-01 2018 3 94.00000 6 2018-04-01 2018 4 97.92857 7 2018-05-01 2018 5 95.75000 

使您的數據值成為原子(年份在其自己的列中,月份在其自己的列中)通常會提高操作的便利性。

或者如果你想使用基本R日期操作而不是lubridate

library(tidyverse)

dfYrMon_base <- 
    df1 %>% 
    mutate(date = as.Date(paste("01/", month, sep = ""), "%d/%m/%Y"),
           year = format(as.Date(date, format="%d/%m/%Y"),"%Y"),
           month = format(as.Date(date, format="%d/%m/%Y"),"%m")
          ) %>%
    arrange(year, month) %>%
    select(date, year, month, result)

dfYrMon_base

請注意創建的數據類型。

 # A tibble: 7 x 4 date year month result <date> <chr> <chr> <dbl> 1 2017-11-01 2017 11 98.66667 2 2017-12-01 2017 12 97.78947 3 2018-01-01 2018 01 96.13636 4 2018-02-01 2018 02 96.40000 5 2018-03-01 2018 03 94.00000 6 2018-04-01 2018 04 97.92857 7 2018-05-01 2018 05 95.75000 

我們可以將它轉換為yearmon類,然后執行order

library(zoo)
out <- df1[order(as.yearmon(df1$month, "%m/%Y"), df1$Result),]
row.names(out) <- NULL
out
#    month   Result
#1 11/2017 98.66667
#2 12/2017 97.78947
#3 01/2018 96.13636
#4 02/2018 96.40000
#5 03/2018 94.00000
#6 04/2018 97.92857
#7 05/2018 95.75000

數據

df1 <- structure(list(month = c("01/2018", "02/2018", "03/2018", "04/2018", 
"05/2018", "11/2017", "12/2017"), Result = c(96.13636, 96.4, 
94, 97.92857, 95.75, 98.66667, 97.78947)), .Names = c("month", 
"Result"), class = "data.frame", 
row.names = c("1", "2", "3", 
"4", "5", "6", "7"))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM