How to sort a data frame by date

前端 未结 7 743
孤城傲影
孤城傲影 2020-11-28 21:46

I need to sort a data frame by date in R. The dates are all in the form of \"dd/mm/yyyy\". The dates are in the 3rd column. The column header is V3. I have seen how to s

相关标签:
7条回答
  • 2020-11-28 22:01

    In case you want to sort dates with descending order the minus sign doesn't work with Dates.

    out <- DF[rev(order(as.Date(DF$end))),]
    

    However you can have the same effect with a general purpose function: rev(). Therefore, you mix rev and order like:

    #init data
    DF <- data.frame(ID=c('ID3', 'ID2','ID1'), end=c('4/1/09 12:00', '6/1/10 14:20', '1/1/11 11:10')
    #change order
    out <- DF[rev(order(as.Date(DF$end))),]
    

    Hope it helped.

    0 讨论(0)
  • 2020-11-28 22:02

    Nowadays, it is the most efficient and comfortable to use lubridate and dplyr libraries.

    lubridate contains a number of functions that make parsing dates into POSIXct or Date objects easy. Here we use dmy which automatically parses dates in Day, Month, Year formats. Once your data is in a date format, you can sort it with dplyr::arrange (or any other ordering function) as desired:

    d$V3 <- lubridate::dmy(d$V3)
    dplyr::arrange(d, V3)
    
    0 讨论(0)
  • 2020-11-28 22:13

    You can use order() to sort date data.

    # Sort date ascending order
    d[order(as.Date(d$V3, format = "%d/%m/%Y")),]
    
    # Sort date descending order
    d[rev(order(as.Date(d$V3, format = "%d/%m/%y"))),]
    

    Hope this helps,

    Link to my quora answer https://qr.ae/TWngCe

    Thanks

    0 讨论(0)
  • 2020-11-28 22:13

    If you have a dataset named daily_data:

    daily_data<-daily_data[order(as.Date(daily_data$date, format="%d/%m/%Y")),] 
    
    0 讨论(0)
  • 2020-11-28 22:15

    The only way I found to work with hours, through an US format in source (mm-dd-yyyy HH-MM-SS PM/AM)...

    df_dataSet$time <- as.POSIXct( df_dataSet$time , format = "%m/%d/%Y %I:%M:%S %p" , tz = "GMT")
    class(df_dataSet$time)
    df_dataSet <- df_dataSet[do.call(order, df_dataSet), ] 
    
    0 讨论(0)
  • 2020-11-28 22:16

    If you just want to rearrange dates from oldest to newest in r etc. you can always do:

    dataframe <- dataframe[nrow(dataframe):1,]
    

    It's saved me exporting in and out from excel just for sort on Yahoo Finance data.

    0 讨论(0)
提交回复
热议问题