Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (7.3k points)

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 = c(1, 3, 8, 3, 2))

#   C A B

# 1 0 4 1

# 2 2 2 3

# 3 4 4 8

# 4 7 7 3

# 5 8 8 2

I like to order the columns by column names alphabetically, to achieve

#   A B C

# 1 4 1 0

# 2 2 3 2

# 3 4 8 4

# 4 7 3 7

# 5 8 2 8

For others I want my own defined order:

#   B A C

# 1 4 1 0

# 2 2 3 2

# 3 4 8 4

# 4 7 3 7

# 5 8 2 8

Please note that my datasets are huge, with 10000 variables. So the process needs to be more automated.

1 Answer

0 votes
by

To sort the columns of a data frame by column name, you can use the order function on the names, and use that to order the columns when subsetting.i.e.,

test[ , order(names(test))]

  A B C

1 4 1 0

2 2 3 2

3 4 8 4

4 7 3 7

5 8 2 8

For your own defined order, you will need to define your own mapping of the names to the ordering and then swapping with the function that would to this with order above, should give your desired output.

For example:

myorder = c("B", "A", "C")

test[,myorder]

  B A C

1 1 4 0

2 3 2 2

3 8 4 4

4 3 7 7

5 2 8 8

Browse Categories

...