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

前端 未结 3 1775
失恋的感觉
失恋的感觉 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:40

    A5C1D2H2I1M1N2O1R2T1's solution didn't work for my data (I've a similar problem that Yilun Zhang) so I found another option:

    mydf <- data.frame(A = 1:2, B = 3:4, C = 5:6)
    #   A B C
    # 1 1 3 5
    # 2 2 4 6
    matches <- c("B", "C", "A") #desired order
    
    mydf_reorder <- mydf[,match(matches, colnames(mydf))]
    colnames(mydf_reorder)
    #[1] "B" "C" "A"
    

    match() find the the position of first element on the second one:

    match(matches, colnames(mydf))
    #[1] 2 3 1
    

    I hope this can offer another solution if anyone is having problems!

提交回复
热议问题