Sort columns of a dataframe by column name

后端 未结 9 521
自闭症患者
自闭症患者 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:26

    An alternative option is to use str_sort() from library stringr, with the argument numeric = TRUE. This will correctly order column that include numbers not just alphabetically:

    str_sort(c("V3", "V1", "V10"), numeric = TRUE)

    # [1] V1 V3 V11

    0 讨论(0)
  • 2020-11-27 11:27
    test = data.frame(C=c(0,2,4, 7, 8), A=c(4,2,4, 7, 8), B=c(1, 3, 8,3,2))
    

    Using the simple following function replacement can be performed (but only if data frame does not have many columns):

    test <- test[, c("A", "B", "C")]
    

    for others:

    test <- test[, c("B", "A", "C")]
    
    0 讨论(0)
  • 2020-11-27 11:27

    Similar to other syntax above but for learning - can you sort by column names?

    sort(colnames(test[1:ncol(test)] ))
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-27 11:32
      test[,sort(names(test))]
    

    sort on names of columns can work easily.

    0 讨论(0)
  • 2020-11-27 11:45

    Here is what I found out to achieve a similar problem with my data set.

    First, do what James mentioned above, i.e.

    test[ , order(names(test))]
    

    Second, use the everything() function in dplyr to move specific columns of interest (e.g., "D", "G", "K") at the beginning of the data frame, putting the alphabetically ordered columns after those ones.

    select(test, D, G, K, everything())
    

    ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

    0 讨论(0)
提交回复
热议问题