Move a column conveniently

前端 未结 4 2180
误落风尘
误落风尘 2021-01-04 11:49

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 :

4条回答
  •  佛祖请我去吃肉
    2021-01-04 12:47

    I found an interesting function (moveMe, written by @A5C1D2H2I1M1N2O1R2T1) that closely fits the problem:

    source('https://raw.githubusercontent.com/mrdwab/SOfun/master/R/moveMe.R')
    
    head(iris[ moveMe(names(iris), 'Species before Sepal.Width') ], 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
    
    
    head(iris[ moveMe(names(iris), 'Species after Sepal.Width') ], 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
    

    It also allows for more complex instructions:

    head(iris[ moveMe(names(iris), 'Species after Sepal.Width; Petal.Width first; Sepal.Length last') ], 2)
    #   Petal.Width Sepal.Width Species Petal.Length Sepal.Length
    # 1         0.2         3.5  setosa          1.4          5.1
    # 2         0.2         3.0  setosa          1.4          4.9
    

提交回复
热议问题