Several times, I've hit a need for converting two columns of a grouped dataframe into a list where the grouping column becomes the name of the list and the values of the non-grouped column become the elements.
For example, given the starwars
dataset, say we want to list characters by their homeworld.
library(tidyverse)
starwars %>%
select(homeworld, name) %>%
group_by(homeworld)
#> # A tibble: 87 x 2
#> # Groups: homeworld [49]
#> homeworld name
#> <chr> <chr>
#> 1 Tatooine Luke Skywalker
#> 2 Tatooine C-3PO
#> 3 Naboo R2-D2
#> 4 Tatooine Darth Vader
#> 5 Alderaan Leia Organa
#> 6 Tatooine Owen Lars
#> 7 Tatooine Beru Whitesun lars
#> 8 Tatooine R5-D4
#> 9 Tatooine Biggs Darklighter
#> 10 Stewjon Obi-Wan Kenobi
#> # ... with 77 more rows
How can I convert this into a list with the homeworld
as names? That is, for the output above, we'd get:
#> $Alderaan
#> [1] "Leia Organa"
#>
#> $Naboo
#> [1] "R2-D2"
#>
#> $Stewjon
#> [1] "Obi-Wan Kenobi"
#>
#> $Tatooine
#> [1] "Luke Skywalker" "C-3PO" "Darth Vader"
#> [4] "Owen Lars" "Beru Whitesun lars" "R5-D4"
#> [7] "Biggs Darklighter"
Credit to @thelatemail, use split:
split(df$name,df$homeworld)
Output:
$Alderaan
[1] "Leia Organa"
$Naboo
[1] "R2-D2"
$Stewjon
[1] "Obi-Wan Kenobi"
$Tatooine
[1] "Luke Skywalker" "C-3PO" "Darth Vader"
[4] "Owen Lars" "Beru Whitesun lars" "R5-D4"
[7] "Biggs Darklighter"
Sample data:
require(data.table)
df <- fread("homeworld, name
Tatooine, Luke Skywalker
Tatooine, C-3PO
Naboo, R2-D2
Tatooine, Darth Vader
Alderaan, Leia Organa
Tatooine, Owen Lars
Tatooine, Beru Whitesun lars
Tatooine, R5-D4
Tatooine, Biggs Darklighter
Stewjon, Obi-Wan Kenobi")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With