Rosalin August
Rosalin August

Reputation: 137

Change the order of numerically named columns in r

If I have a dataframe like the one below which has numerical column names

example = data.frame(1=c(1,8,3,9), 2=c(3,2,3,3), 3=c(5,2,5,4), 4=c(1,2,3,4), 5=c(2,5,7,8))

Which looks like this:

1 2 3 4 5
1 3 5 1 2
8 2 2 2 5
3 3 5 3 7
9 3 4 4 8

And I want to arrange it so that the column names start with three and proceed through five and back to one, like this:

3 4 5 1 2
5 1 2 1 3
2 2 5 8 2
5 3 7 3 3 
4 4 8 9 3 

I know how to rearrange the position of a single column in a dataset, but I'm not sure how to do this with more than one column in this particular order.

Upvotes: 1

Views: 232

Answers (2)

akrun
akrun

Reputation: 887158

We can use the column index concatenated (c) based on the sequence (:) on a range of values

example[c(3:5, 1:2)]
#   3 4 5 1 2
#1 5 1 2 1 3
#2 2 2 5 8 2
#3 5 3 7 3 3
#4 4 4 8 9 3

As the column names are all numeric, just convert to numeric and use that for ordering

v1 <- as.numeric(names(example))
example[c(v1[3:5], v1[1:2])]

Or simply do

example[c(names(example)[3:5], names(example)[1:2])]

Or another way is with head and tail

example[c(tail(names(example), 3), head(names(example), 2))]

data

example <- data.frame(`1`=c(1,8,3,9), `2`=c(3,2,3,3),
   `3`=c(5,2,5,4), `4`=c(1,2,3,4), `5`=c(2,5,7,8), check.names = FALSE)

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388982

R will not easily let you create columns with numbers as name. If somehow, you are able to create columns with numbers you can use match to get order in which you want the column names.

example[match(c(3:5, 1:2), names(example))]

#  3 4 5 1 2
#1 5 1 2 1 3
#2 2 2 5 8 2
#3 5 3 7 3 3
#4 4 4 8 9 3

Upvotes: 0

Related Questions