Home > database >  Sort columns by names (only specific columns)
Sort columns by names (only specific columns)

Time:09-28

For example I have dataframe like this :

test = data.frame(C = c(0, 2, 4, 7, 8), A = c(4, 2, 4, 7, 8), B = c(1, 3, 8, 3, 2), Z = c(6, 7, 3, 3, 1), D = c(1, 8, 9, 9, 5))

and I want sort only the 3 last columns by names. I try this one, but it's not working :

test[3:5] <- test[3:5][ , order(names(test[3:5]))]

The result should be like this:

C     A     B     D     Z
0     4     1     1     6
2     2     3     8     7
...   ...   ...   ...   ...

CodePudding user response:

One option via dplyr::select()

dplyr::select(test, names(test)[1:2], sort(names(test)[3:5]))

Output:

 C A B D Z
1 0 4 1 1 6
2 2 2 3 8 7
3 4 4 8 9 3
4 7 7 3 9 3
5 8 8 2 5 1

CodePudding user response:

In base R (distinctly uglier than the dplyr::select() solution):

n <- names(test)
nc <- ncol(test)
test[, c(n[1:(nc - 3)], sort(n[(nc - 2):nc]))]
#  C A B D Z
#1 0 4 1 1 6
#2 2 2 3 8 7
#3 4 4 8 9 3
#4 7 7 3 9 3
#5 8 8 2 5 1

CodePudding user response:

A two step Base

#Move the data
test[3:5]<-test[3:5][order(names(test[3:5]))]
#Rearange the column names
names(test)<-c(names(test[1:2]), names(test[3:5][order(names(test[3:5]))]))

CodePudding user response:

base R

cbind(test[,1:2],test[,sort(names(test)[3:5])])

or (slightly faster)

test[,c(names(test)[1:2],sort(names(test)[-(1:2)]))]

Output:

  C A B D Z
1 0 4 1 1 6
2 2 2 3 8 7
3 4 4 8 9 3
4 7 7 3 9 3
5 8 8 2 5 1
  • Related