Home > Enterprise >  R - set list element names from strings they contain using tidyverse
R - set list element names from strings they contain using tidyverse

Time:07-01

Let's say you have a list like this one:

cityhoods <- list("Zagreb/Donji Grad",
               "Berlin/Mitte",
               "Warsaw/Stare Miasto")

Now if I want the list elements to have names "Zagreb", "Berlin" and "Warsaw", I could of course do this:

names(cityhoods) <- c("Zagreb", "Berlin", "Warsaw")

However, I have a very large number of list elements, not just 3 like in this example, and I am doing all the previous operations within a pipeline. I was wondering what would be a pipe-friendly way to pull the city name from the list element and then assign it as the name of the list element.

CodePudding user response:

You can do:

gsub("/.*", "", cityhoods)

CodePudding user response:

library(tidyverse)

cityhoods <- list("Zagreb/Donji Grad",
                  "Berlin/Mitte",
                  "Warsaw/Stare Miasto")

cityhoods %>%  
  str_extract(".*(?=/)")

#> [1] "Zagreb" "Berlin" "Warsaw"

Created on 2022-06-30 by the reprex package (v2.0.1)

CodePudding user response:

You can use setNames like this:

cityhoods <- list("Zagreb/Donji Grad",
                  "Berlin/Mitte",
                  "Warsaw/Stare Miasto")

setNames(cityhoods, c("Zagreb", "Berlin", "Warsaw"))
#> $Zagreb
#> [1] "Zagreb/Donji Grad"
#> 
#> $Berlin
#> [1] "Berlin/Mitte"
#> 
#> $Warsaw
#> [1] "Warsaw/Stare Miasto"

Created on 2022-06-30 by the reprex package (v2.0.1)

  •  Tags:  
  • r
  • Related