Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R move column to last using dplyr

Tags:

r

dplyr

For a data.frame with n columns, I would like to be able to move a column from any of 1-(n-1) positions, to be the nth column (i.e. a non-last column to be the last column). I would also like to do it using dplyr. I would like to do so without simply typing out the names of all the columns.

For example:

data<-data.frame(a=1:5, b=6:10, c=11:15) 

This works, but isn't the dplyr way:

data[,c(colnames(data)[colnames(data)!='b'],'b')] 

This is the dplyr way to make column b first:

data%>%select(b, everything()) 

But this doesn't work to make column b last:

data%>%select(everything(), b) 

This works, but requires me to type out all the columns:

data%>%select(a,c,b) 

So is there an elegant dplyr way to do this?

Related questions:

  • move column to first in a data frame
  • How does one reorder columns in a data frame?
like image 418
dule arnaux Avatar asked May 10 '17 16:05

dule arnaux


People also ask

How do I change the order of columns in a Dataframe in R?

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.

How do you rearrange the order of a column in a data set using dplyr functions?

The dplyr function arrange() can be used to reorder (or sort) rows by one or more variables. Instead of using the function desc(), you can prepend the sorting variable by a minus sign to indicate descending order, as follow. If the data contain missing values, they will always come at the end.

Can you rearrange columns in R?

It's possible to reorder columns by either column position (i.e., number) or column names.


1 Answers

After some tinkering, the following works and requires very little typing.

data %>% select(-b,b)


UPDATE: dplyr 1.0.0

dplyr 1.0.0 introduces the relocate verb:

data %>% relocate(b, .after = last_col())

I still prefer the old "hacky" way.

like image 165
dule arnaux Avatar answered Sep 20 '22 19:09

dule arnaux