string_dat <- structure(list(ID = c(2455, 2455), Location = c("c(\"Southside of Dune\", \"The Hogwarts Express\")",
"Vertex, Inc.")), class = "data.frame", row.names = c(NA, -2L
))
> string_dat
ID Location
1 2455 c("Southside of Dune", "The Hogwarts Express")
2 2455 Vertex, Inc.
I would like to expand the data.frame above based on Location.
library(tidyr)
> string_dat %>% tidyr::separate_rows(Location, sep = ",")
# A tibble: 4 × 2
ID Location
<dbl> <chr>
1 2455 "c(\"Southside of Dune\""
2 2455 " \"The Hogwarts Express\")"
3 2455 "Vertex"
4 2455 " Inc."
Splitting just on , wrongly split Vertex, Inc. into two entries. Also it did not take care of c(\" and \"" for the first two strings.
I also tried to remove the c(\" at the beginning by using gsub, but it gave me the following error.
> gsub('c(\"', "", x = string_dat$Location)
Error in gsub("c(\"", "", x = string_dat$Location) :
invalid regular expression 'c("', reason 'Missing ')''
My desired output is
# A tibble: 3 × 2
ID Location
<dbl> <chr>
1 2455 "Southside of Dune"
2 2455 "The Hogwarts Express"
3 2455 "Vertex, Inc."
********** Edit **********
library(tidyverse)
string_dat %>%
mutate(
# mark twin elements with `;`:
Location = str_replace(Location, '",', '";'),
# remove string-first `c` and all non-alphanumeric characters
# except `,`, `.`, and `;`:
Location = str_replace_all(Location, '^c|(?![.,; ])\\W', '')) %>%
separate_rows(Location, sep = '; ')
# A tibble: 3 × 2
ID Location
<dbl> <chr>
1 2455 "c(\"Southside of Dune\""
2 2455 "\"The Hogwarts Express\")"
3 2455 "Vertex, Inc."