Search code examples
rdatedplyrreorderlist

sorting list of dataframes by date


I have a list of dataframes in a structure similar to this:

`ID1_01/05/10` <- data.frame(c(1,1))
`ID1_21/02/10` <- data.frame(c(2,1))
`ID2_01/05/10` <- data.frame(c(3,1))
`ID2_21/02/10` <- data.frame(c(4,1))
lst <- list(mget ( ls ( pattern = 'ID\\d+')))

I'd like to order them in the list first by identity and then by date. I.e.:

`ID1_21/02/10`
`ID1_01/05/10`
`ID2_21/02/10`
`ID2_01/05/10`

Is there a way of doing this easily?


Solution

  • We extract the names, get the numeric part ('v1') and the Date part, and order based on it

    nm1 <-  sapply(lst, names)[,1]
    v1 <- as.numeric(sub(".*(\\d+)_.*", "\\1", nm1))
    d1 <- as.Date(sub(".*_", "", nm1), "%d/%m/%y")
    nm1[order(v1, d1)]
    #[1] "ID1_21/02/10" "ID1_01/05/10" "ID2_21/02/10" "ID2_01/05/10"
    
    lapply(lst, function(x) x[order(v1, d1)])
    #[[1]]
    #[[1]]$`ID1_21/02/10`
    # c.2..1.
    #1       2
    #2       1
    
    #[[1]]$`ID1_01/05/10`
    #  c.1..1.
    #1       1
    #2       1
    
    #[[1]]$`ID2_21/02/10`
    #  c.4..1.
    #1       4
    #2       1
    
    #[[1]]$`ID2_01/05/10`
    #  c.3..1.
    #1       3
    #2       1
    

    Update

    In the OP's example, the mget was wrapped with list and it would create a list of lists. Instead it would be

    lst <- mget ( ls ( pattern = 'ID\\d+'))
    

    and if that is the case, then

    nm1 <- names(lst)
    lst[order(v1, d1)]