将正则表达式与向量相结合以在 R 中进行文本替换

Combining Regular Expressions with Vectors for Text Substitution in R

我有一个数据框,其中包含我从 Spotify 抓取的曲目标题、艺术家和音乐流派的列。在 R 中的再现性:

a <- c("Run the World (Girls)", "LOCO", "Habits", "Never Born - 2017 Version")
b <- c("Beyoncé", "NERVO", "Marmozets", "Guano Apes")
c <- c("dance pop pop post-teen pop r&b", "australian dance big room deep big room edm electro house house progressive electro house progressive house", "alt-indie rock british alternative rock pixie", "alternative metal funk metal nu metal post-grunge rap metal rap rock")
df <- data.frame(SONG=a, ARTIST=b, GENRE=c)

编辑以包括实际的表格输入和所需的输出。

这是如上所述的输入数据帧。

我想清理流派以供分析。目前我创建了一个常见流派列表:

main_genres <- c("hip hop", "pop", "country", "latin", "dance", "rock", "classical", "jazz", "indie", "folk", "metal", "reggae", "punk")

我已经为我最终想做的事情创建了一个新的数据框。

all_main_genres <- data.frame(TRACK = character(), ARTIST = character(), GENRE = character())

我想知道是否有一种 non-loop 方法可以在 dfGENRE 列中搜索 main_genres 中的任何和所有字符串] 向量,如果是,则在 all_main_genres 中创建一个包含原始歌曲名称和歌曲艺术家的新行,并在新的 GENRE 列中创建 MATCHED 流派来自 main_genres.

例如,all_main_genres 中的第一行将是

TRACK = 运行 世界(女孩)

艺术家 = 碧昂丝

类型 = 舞蹈

这是因为 dfGENRE 的第一行匹配 main_genres 向量中的 "dance" 和 "pop"。因为有两个匹配项,所以 all_main_genres 的第二行将是:

TRACK = 运行 世界(女孩)

艺术家 = 碧昂丝

流派 = 流行

然后第三行是 NERVO 的歌曲,类型为 dance,第三行是 Marmozets 的歌曲,类型为 indie 然后是 rock 等类型的 Marmozets 歌曲

换句话说,它应该是这样的:

我用了 sapplygrepl

sapply(main_genres, grepl, playlist_genres$GENRE[row], ignore.case = TRUE)

向量匹配有效,但我不确定如何将其扩展到 gsub 并使用潜在替代的向量,这些潜在替代本身将充当被替代的内容。 还没有用矢量看到这个,所以如果它是转贴请原谅。提前致谢。

df%>%
     tidytext::unnest_tokens(GENRE,GENRE,stringr::str_extract_all,pattern=glue::collapse(main_genres,"|"))%>%
     unique%>%
     `rownames<-`(NULL)
                       SONG     ARTIST GENRE
1     Run the World (Girls)    Beyoncé dance
2     Run the World (Girls)    Beyoncé   pop
3                      LOCO      NERVO dance
4                    Habits  Marmozets indie
5                    Habits  Marmozets  rock
6 Never Born - 2017 Version Guano Apes metal
7 Never Born - 2017 Version Guano Apes  rock

要在 base R 中执行此操作:您将执行:

GENRE=regmatches(df$GENRE,gregexpr(paste(main_genres,collapse = "|"),df$GENRE))
unique(transform(df[rep(1:nrow(df),lengths(GENRE)),1:2],GENRE=unlist(GENRE),row.names=NULL))
                        SONG     ARTIST GENRE
1      Run the World (Girls)    Beyoncé dance
2      Run the World (Girls)    Beyoncé   pop
5                       LOCO      NERVO dance
6                     Habits  Marmozets indie
7                     Habits  Marmozets  rock
9  Never Born - 2017 Version Guano Apes metal
13 Never Born - 2017 Version Guano Apes  rock