dply: order columns alphabetically in R

前端 未结 4 913
清歌不尽
清歌不尽 2020-12-23 20:08

If I have a large DF (hundreds and hundreds) columns with different col_names randomly distributed alphabetically:

df.x <- data.frame(2:11, 1:10, rnorm(1         


        
相关标签:
4条回答
  • 2020-12-23 20:16

    If a specific column (or columns) has to be the first one (or last), but the rest is ordered, you can:

    mtcars %>% tibble %>% 
      select("hp", sort(colnames(.)))
    
    0 讨论(0)
  • 2020-12-23 20:23

    Why not just:

    sort(colnames(df.x))
    
    [1] "delta"  "ID"     "string"
    
    0 讨论(0)
  • An alternative way to do this in dplyr is:

    iris %>% 
      select(sort(current_vars()))
    

    current_vars() returns column names such that they're sortable, and select() will take the vector of column names.

    0 讨论(0)
  • 2020-12-23 20:40

    Try this

    df %>% select(noquote(order(colnames(df))))
    

    or just

    df[,order(colnames(df))]
    
    0 讨论(0)
提交回复
热议问题