Sort columns of a dataframe by column name

后端 未结 9 634
自闭症患者
自闭症患者 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: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())
    

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

提交回复
热议问题