【发布时间】:2019-03-10 14:36:03
【问题描述】:
问题:
我想创建一个与长字符串列匹配的字符串的数据框。在数据框“d”中,流派列是具有不同流派的字符串列。出现问题是因为每行匹配的项目数量不同。
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
我的不雅方式
我找到了一个工作流程来解决这个问题,这有点不雅。首先,提取与str_extract_all 和simplify = T 的所有匹配项,这将返回一个数据框。然后用列名创建一个向量字符串,分配给提取的数据框,最后使用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>
由reprex package (v0.2.1) 于 2019-03-10 创建
我想知道是否有办法在管道运算符、mutate 或 map_df 中以一种 tidyverse 的方式实现它...我确信有更好的方法来做到这一点。
【问题讨论】:
-
你为什么不使用
jsonlite包像JSON一样处理它们,这样使用键值对会容易得多 -
这是一个通用数据框,我有更多没有 json 模式的列,但有同样的问题。
-
@TitoSanz 您能否在示例数据集中包含“没有 json 模式但存在相同问题”的列?