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(10)) colnames(df.x) <- c("ID", "string", "delta")
How would I order all of the data (vertically) by col_name alphabetically?
Essentially, I have hundreds of CSV(sep="|") text files that I need to read their columns into a single df, order those columns alphabetically and then use some other dplyf functions to get a final result. I have all of this figured out except how to order the columns alphabetically. I do not want to sort the columns (up and down) by alphabet, rather, the actual vertical orientation of the col_names and their corresponding data. Analogous to cutting and pasting entire columns of data in Excel.
For example I reviewed this approach but this is the "sort" the rows alphabetically bit, which is not what I'm looking to do.
How to sort a dataframe by column(s)?
Thanks!
Rearrange or reorder the column Alphabetically in R: Rearranging the column in alphabetical order can be done with the help of select() function & order() function along with pipe operator. In another method it can also be accomplished simply with help of order() function only.
To sort a data frame in R, use the order( ) function. By default, sorting is ASCENDING. Prepend the sorting variable by a minus sign to indicate DESCENDING order.
It's possible to reorder columns by either column position (i.e., number) or column names.
Try this
df %>% select(noquote(order(colnames(df))))
or just
df[,order(colnames(df))]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With