Problem:
I want to create a data frame with strings matched from a long string column. In the data frame "d" the genre column is a string column with different genres. The problem appears because each row hasn't the same numbers of items matched.
library(tidyverse)
d <- structure(list(genres = c("[{'id': 35, 'name': 'Comedy'}]", "[{'id': 35, 'name': 'Comedy'}, {'id': 18, 'name': 'Drama'}, {'id': 10751, 'name': 'Family'}, {'id': 10749, 'name': 'Romance'}]",
"[{'id': 16, 'name': 'Animation'}, {'id': 12, 'name': 'Adventure'}, {'id': 10751, 'name': 'Family'}]"
), budget = c(1.4e+07, 4e+07, 8e+06)), row.names = c(NA, -3L), class = c("tbl_df",
"tbl", "data.frame"))
d
#> # A tibble: 3 x 2
#> genres budget
#> <chr> <dbl>
#> 1 [{'id': 35, 'name': 'Comedy'}] 1.40e7
#> 2 [{'id': 35, 'name': 'Comedy'}, {'id': 18, 'name': 'Drama'}, {'id… 4.00e7
#> 3 [{'id': 16, 'name': 'Animation'}, {'id': 12, 'name': 'Adventure'… 8.00e6
My inelegant way
I have found a workflow to work around with this which is a little inelegant. First, extract all the matches with str_extract_all
with simplify = T
which returns a data frame. Then create a vector string with the column names, assign to the extracted data frame and finally use bind_cols
:
foo <- str_extract_all(d$genres, '(?<=\'name\':\\s\')([^\']*)', simplify = T)
colnames(foo) <- paste0("genre_", 1:ncol(foo), "_extract")
foo <- foo %>% as_tibble()
foo_final <- bind_cols(d, foo)
foo_final
#> # A tibble: 3 x 6
#> genres budget genre_1_extract genre_2_extract genre_3_extract
#> <chr> <dbl> <chr> <chr> <chr>
#> 1 [{'id… 1.40e7 Comedy "" ""
#> 2 [{'id… 4.00e7 Comedy Drama Family
#> 3 [{'id… 8.00e6 Animation Adventure Family
#> # … with 1 more variable: genre_4_extract <chr>
Created on 2019-03-10 by the reprex package (v0.2.1)
I would like to know if there is a way to make it in a tidyverse way within pipe operators, mutate, or map_df... I am sure there is a better way of doing this.