0

I need to order my df in R alphabetically with a lot o columns...

library(dplyr)

df <- data.frame(
  colname = c(
    "a",
    "nb",
    "s",
    "b",
    "c",
    "sd",
    "sdsd",
    "sdsdtr",
    "y",
    "sasa",
    "de",
    "fe",
    "rwew",
    "dsd",
    "ewew"
  ),
  value = seq_along(1:15)
)

df
   colname value
1        a     1
2       nb     2
3        s     3
4        b     4
5        c     5
6       sd     6
7     sdsd     7
8   sdsdtr     8
9        y     9
10    sasa    10
11      de    11
12      fe    12
13    rwew    13
14     dsd    14
15    ewew    15

Suppose I have much more than just 15 columns, as demonstrated here in the small example, how could I use some R function to sort my df columns by column names alphabetically?

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
  • 3
    Do you mean `df[order(df$colname),]`? The question is a little confusing because you ask about columns but your data has 15 rows. – SamR Jul 25 '22 at 13:19
  • 2
    Seems like a duplicate of the [How to sort a data frame by multiple columns? FAQ](https://stackoverflow.com/q/1296646/903061), but it's confusing since you say you have lots of columns, but you only show 2 columns, and only 1 to sort by (`colname`). Can you please clarify? And maybe show what you tried? – Gregor Thomas Jul 25 '22 at 13:36
  • 1
    Or duplicate of: https://stackoverflow.com/questions/7334644/sort-columns-of-a-dataframe-by-column-name judging by the text and not the example. – harre Jul 25 '22 at 13:53

0 Answers0