Sort columns of a dataframe by column name

后端 未结 9 630
自闭症患者
自闭症患者 2020-11-27 10:48

This is possibly a simple question, but I do not know how to order columns alphabetically.

test = data.frame(C = c(0, 2, 4, 7, 8), A = c(4, 2, 4, 7, 8), B =          


        
9条回答
  •  时光说笑
    2020-11-27 11:28

    You can use order on the names, and use that to order the columns when subsetting:

    test[ , order(names(test))]
      A B C
    1 4 1 0
    2 2 3 2
    3 4 8 4
    4 7 3 7
    5 8 2 8
    

    For your own defined order, you will need to define your own mapping of the names to the ordering. This would depend on how you would like to do this, but swapping whatever function would to this with order above should give your desired output.

    You may for example have a look at Order a data frame's rows according to a target vector that specifies the desired order, i.e. you can match your data frame names against a target vector containing the desired column order.

提交回复
热议问题