Skip to content

Instantly share code, notes, and snippets.

@kjhealy
Last active January 22, 2023 18:42
Show Gist options
  • Save kjhealy/44f9eb6ebc3510d650554217b3030314 to your computer and use it in GitHub Desktop.
Save kjhealy/44f9eb6ebc3510d650554217b3030314 to your computer and use it in GitHub Desktop.
## list2env() example
##
## An occasionally useful fn to turn list elements into objects. You usually
## want to keep your dfs etc as some kind of list, because it's much neater,
## but sometimes you want to spit out a bunch of named objects.
## Base R version
## We need to take care not to mislabel the list elements, e.g. by mistakenly
## assuming things about the correspondence between elements and names.
## To see why this is bad try e.g. unique(mtcars$cyl), which will be in
## the "wrong" order if you wanted to use it to name the list elements from
## split(). So we write an anonymous function to name things inline.
mtcars |>
split(mtcars$cyl) |> # Convert to list of three dfs.
(\(x) setNames(x, paste0("cyl", # Name the elements cyl4, cyl6,
names(x))))() |> # cyl8, using an anonymous fn.
list2env(envir = .GlobalEnv) # Turn them into objects.
#> <environment: R_GlobalEnv>
## Now e.g this exists
cyl4
#> mpg cyl disp hp drat wt qsec vs am gear carb
#> Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
#> Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2
#> Merc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2
#> Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
#> Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
#> Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
#> Toyota Corona 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1
#> Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
#> Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
#> Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
#> Volvo 142E 21.4 4 121.0 109 4.11 2.780 18.60 1 1 4 2
## Delete
rm(list= c("cyl4", "cyl6", "cyl8"))
## Tidyverse version
## Again naming the list is the point where it's easy to make an error.
## This is why group_split refuses to return named lists, btw. But we can
## do something similar with map_chr() to get past this. OTOH the fact
## it's kinda awkward is informative! NB use of magrittr pipe here.
library(tidyverse)
mtcars %>%
group_split(cyl) %>%
set_names(map_chr(., ~ paste0("cyl", .x$cyl[1]))) %>%
list2env(envir = .GlobalEnv)
#> <environment: R_GlobalEnv>
## Now e.g this exists again
cyl6
#> # A tibble: 7 × 11
#> mpg cyl disp hp drat wt qsec vs am gear carb
#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 21 6 160 110 3.9 2.62 16.5 0 1 4 4
#> 2 21 6 160 110 3.9 2.88 17.0 0 1 4 4
#> 3 21.4 6 258 110 3.08 3.22 19.4 1 0 3 1
#> 4 18.1 6 225 105 2.76 3.46 20.2 1 0 3 1
#> 5 19.2 6 168. 123 3.92 3.44 18.3 1 0 4 4
#> 6 17.8 6 168. 123 3.92 3.44 18.9 1 0 4 4
#> 7 19.7 6 145 175 3.62 2.77 15.5 0 1 5 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment