Skip to content

Instantly share code, notes, and snippets.

@romainfrancois
Created April 23, 2018 08:16
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romainfrancois/5363c96646bb164f77fac2610d23b126 to your computer and use it in GitHub Desktop.
Save romainfrancois/5363c96646bb164f77fac2610d23b126 to your computer and use it in GitHub Desktop.
select columns to front and back
library(purrr)
library(rlang)
#> 
#> Attaching package: 'rlang'
#> The following objects are masked from 'package:purrr':
#> 
#>     %@%, %||%, as_function, flatten, flatten_chr, flatten_dbl,
#>     flatten_int, flatten_lgl, invoke, list_along, modify, prepend,
#>     rep_along, splice
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

back <- function(data, ...){
  dots <- quos(...)

  # negate each expression
  ndots <- map(dots, function(q) expr(-!!q) )

  # select the negated (rm the columns) and then select them back
  select( data, !!!ndots, !!!dots )
}

front <- function(data, ...){
  select( data, ..., everything() )
}

back(iris, Species) %>% head
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1          5.1         3.5          1.4         0.2  setosa
#> 2          4.9         3.0          1.4         0.2  setosa
#> 3          4.7         3.2          1.3         0.2  setosa
#> 4          4.6         3.1          1.5         0.2  setosa
#> 5          5.0         3.6          1.4         0.2  setosa
#> 6          5.4         3.9          1.7         0.4  setosa
back(iris, Species, starts_with("Petal")) %>% head
#>   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
#> 3          4.7         3.2  setosa          1.3         0.2
#> 4          4.6         3.1  setosa          1.5         0.2
#> 5          5.0         3.6  setosa          1.4         0.2
#> 6          5.4         3.9  setosa          1.7         0.4

front(iris, Species) %>% head
#>   Species Sepal.Length Sepal.Width Petal.Length Petal.Width
#> 1  setosa          5.1         3.5          1.4         0.2
#> 2  setosa          4.9         3.0          1.4         0.2
#> 3  setosa          4.7         3.2          1.3         0.2
#> 4  setosa          4.6         3.1          1.5         0.2
#> 5  setosa          5.0         3.6          1.4         0.2
#> 6  setosa          5.4         3.9          1.7         0.4

Created on 2018-04-23 by the reprex package (v0.2.0).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment