Sort columns of a dataframe by column name

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

    So to have a specific column come first, then the rest alphabetically, I'd propose this solution:

    test[, c("myFirstColumn", sort(setdiff(names(test), "myFirstColumn")))]
    
    0 讨论(0)
  • 2020-11-27 11:47

    Here's the obligatory dplyr answer in case somebody wants to do this with the pipe.

    test %>% 
        select(sort(names(.)))
    
    0 讨论(0)
  • 2020-11-27 11:52

    If you only want one or more columns in the front and don't care about the order of the rest:

    require(dplyr)
    test %>%
      select(B, everything())
    
    0 讨论(0)
提交回复
热议问题