Hi all,
Does anyone know if there is a way to order columns in a data.frame or tibble by column type?
For example, if the standard gapminder
data set looks like this:
suppressPackageStartupMessages(library(dplyr))
library(gapminder)
glimpse(gapminder)
#> Observations: 1,704
#> Variables: 6
#> $ country <fct> Afghanistan, Afghanistan, Afghanistan, Afghanistan, Af…
#> $ continent <fct> Asia, Asia, Asia, Asia, Asia, Asia, Asia, Asia, Asia, …
#> $ year <int> 1952, 1957, 1962, 1967, 1972, 1977, 1982, 1987, 1992, …
#> $ lifeExp <dbl> 28.801, 30.332, 31.997, 34.020, 36.088, 38.438, 39.854…
#> $ pop <int> 8425333, 9240934, 10267083, 11537966, 13079460, 148803…
#> $ gdpPercap <dbl> 779.4453, 820.8530, 853.1007, 836.1971, 739.9811, 786.…
If we want to move the columns year
and lifeExp
to the front, we could utilize the select
and everything()
function as follows:
gapminder %>% select(year, lifeExp, everything()) %>% glimpse()
#> Observations: 1,704
#> Variables: 6
#> $ year <int> 1952, 1957, 1962, 1967, 1972, 1977, 1982, 1987, 1992, …
#> $ lifeExp <dbl> 28.801, 30.332, 31.997, 34.020, 36.088, 38.438, 39.854…
#> $ country <fct> Afghanistan, Afghanistan, Afghanistan, Afghanistan, Af…
#> $ continent <fct> Asia, Asia, Asia, Asia, Asia, Asia, Asia, Asia, Asia, …
#> $ pop <int> 8425333, 9240934, 10267083, 11537966, 13079460, 148803…
#> $ gdpPercap <dbl> 779.4453, 820.8530, 853.1007, 836.1971, 739.9811, 786.…
If we want to only keep the columns of type integer
, we could use the select_if()
and is.integer
functions as follows:
gapminder %>% select_if(is.integer) %>% glimpse()
#> Observations: 1,704
#> Variables: 2
#> $ year <int> 1952, 1957, 1962, 1967, 1972, 1977, 1982, 1987, 1992, 1997,…
#> $ pop <int> 8425333, 9240934, 10267083, 11537966, 13079460, 14880372, 1…
What if we wanted to combine the two? For example if we wanted to programmatically move the integer
columns to the front, but keep the rest.
Thanks!
Created on 2019-08-08 by the reprex package (v0.3.0)