代码之家  ›  专栏  ›  技术社区  ›  Mus mzuba

如何根据特定列的日期值重新排序?

  •  -1
  • Mus mzuba  · 技术社区  · 6 年前

    我有一个脚本,它生成一个.csv输出,如下所示:

    enter image description here

    但是,我强调了一个问题:日期命名列的顺序不总是正确的。

    我试图按名称对列进行排序,但这会影响前三列( retailer , department , type )必须始终在前三列中。这是因为它们首先按日期排序,然后按字符值排序。

    如何重新排列列的顺序,使前三列保持原来的位置,并以正确的顺序获取日期?

    更新:

    我可以这样排序列,这是解决方案的第一部分:

    sort(names(output))
    

    在这种格式中,我现在需要将最后三列移到开头(对于生成的每个数据帧,这总是相同的,所以很好)。

    我怎样才能做到这一点?

    1 回复  |  直到 6 年前
        1
  •  1
  •   akrun    6 年前

    一种选择是转换为 Date 上课然后点菜

    # using a pattern, get the column index
    i1 <- grep("^\\d{2}", names(df1))
    # sort the extracted the column names after converting to 'Date' class
    nm1 <-  names(df1)[i1][order(as.Date(names(df1)[i1], '%d/%m/%Y'))]
    # get the names of the other columns
    nm2 <- setdiff(names(df1), names(df1)[i1])
    # concatenate the columns
    df2 <- df1[c(nm2, nm1)]
    df2
    #    retailer department      type 22/03/2015 15/01/2017 25/07/2018 11/01/2019 12/01/2019
    #1        1          a completed          4          1          2          4          1
    #2        2          b completed          1          1          2          3          4
    #3        3          c completed          5          1          2          2          3
    

    数据

    df1 <- data.frame(retailer = 1:3, department = letters[1:3], 
     type = 'completed', `11/01/2019` = c(4, 3, 2),
     `12/01/2019` = c(1, 4, 3), `15/01/2017` = 1,
     `25/07/2018` = 2, `22/03/2015` = c(4, 1, 5), check.names = FALSE)