R: Sort columns of a data frame by a vector of column names

前端 未结 3 1784
失恋的感觉
失恋的感觉 2020-12-16 22:27

I have a data.frame that looks like this: \"enter

which has 1000+ columns with similar

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-16 22:39

    Brodie's answer does exactly what you're asking for. However, you imply that your data are large, so I will provide an alternative using "data.table", which has a function called setcolorder that will change the column order by reference.

    Here's a reproducible example.

    Start with some simple data:

    mydf <- data.frame(A = 1:2, B = 3:4, C = 5:6)
    matches <- data.frame(X = 1:3, Y = c("C", "A", "B"), Z = 4:6)
    mydf
    #   A B C
    # 1 1 3 5
    # 2 2 4 6
    matches
    #   X Y Z
    # 1 1 C 4
    # 2 2 A 5
    # 3 3 B 6
    

    Provide proof that Brodie's answer works:

    out <- mydf[matches$Y]
    out
    #   C A B
    # 1 5 1 3
    # 2 6 2 4
    

    Show a more memory efficient way to do the same thing.

    library(data.table)
    setDT(mydf)
    mydf
    #    A B C
    # 1: 1 3 5
    # 2: 2 4 6
    
    setcolorder(mydf, as.character(matches$Y))
    mydf
    #    C A B
    # 1: 5 1 3
    # 2: 6 2 4
    

提交回复
热议问题