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:
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.
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.
It's possible to reorder columns by either column position (i.e., number) or column names.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With