Move a column conveniently

  • A+
Category:Languages

There are great questions and answers on how to move a column to the first or last place.

Using dplyr The best answers are respectively analog to :

iris %>% select( Sepal.Width, everything()) %>% head(2) # move Sepal.Width to first #   Sepal.Width Sepal.Length Petal.Length Petal.Width Species # 1         3.5          5.1          1.4         0.2  setosa # 2         3.0          4.9          1.4         0.2  setosa  iris %>% select(-Sepal.Width, Sepal.Width) %>% head(2) # move Sepal.Width to last #   Sepal.Length Petal.Length Petal.Width Species Sepal.Width # 1          5.1          1.4         0.2  setosa         3.5 # 2          4.9          1.4         0.2  setosa         3.0 

However I didn't find any easy way to move a column after or before a given one.

I'm posting a rough solution below but :

  • I find it clunky
  • it doesn't leverage the flexibility of tidyverse functions to use numeric indices, names, strings etc...

I believe using vars we could also move a list of columns, or a group of column showing a pattern in the names etc... But I'm not yet so comfortable with tidyverse style programming.

So I challenge you to do better/smarter or point me to the obvious solution I've missed.

Expected output :

iris %>% move_at(Species, Sepal.Width, side = "before") %>% head(2)  #   Sepal.Length Species Sepal.Width Petal.Length Petal.Width # 1          5.1  setosa         3.5          1.4         0.2 # 2          4.9  setosa         3.0          1.4         0.2  iris %>% move_at(Species, Sepal.Width, side = "after") %>% head(2) #   Sepal.Length Sepal.Width Species Petal.Length Petal.Width # 1          5.1         3.5  setosa          1.4         0.2 # 2          4.9         3.0  setosa          1.4         0.2 

 


This seems to work:

iris %>% select(1:Sepal.Width, Species, everything()) %>% head(2) #>   Sepal.Length Sepal.Width Species Petal.Length Petal.Width #> 1          5.1         3.5  setosa          1.4         0.2 #> 2          4.9         3.0  setosa          1.4         0.2 iris %>% select(1:Sepal.Width, -Sepal.Width, Species, everything()) %>% head(2) #>   Sepal.Length Species Sepal.Width Petal.Length Petal.Width #> 1          5.1  setosa         3.5          1.4         0.2 #> 2          4.9  setosa         3.0          1.4         0.2 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: