我有一个要从样本数据集中提取的颜色列表。似乎错过了一些颜色,找到了其他颜色。
color_list <- c("gray", "brown", "green", "plum", "mist", "forest", "sienna", "grape", "ruby", "emerald", "copper",
"silver", "gold", "blue")
str_extract(df, fixed(color_list, ignore_case = TRUE))
[1] "GRAY" NA NA NA NA NA NA NA NA NA NA "silver" "GOLD" "blue"
然而,第一个比赛应该是“银色”。
样本数据:
structure(list(df = c("Tsilver flash mirror", "E:~ ADD FLASH FRONT MI",
"E:~", "E##T Color: G 15#3; MC", "E:~ ## PLEASE USE 8 BA", "E:~ ## blue flash ##",
"E:~ ## Silver Mirror #", "Ssilver mirror", "E:~ ## Treatment: Fee-",
"E:~Further Instruction", "E:~ ## FORREST GRAY Xp", "ESILVER",
"EGOLD")), class = "data.frame", row.names = c("1", "2", "3",
"4", "5", "6", "7", "8", "9", "10", "11", "12", "13"))
还有可能与Str_Extract进行“模糊”匹配吗?由于数据中存在一些拼写错误的颜色。
答案 0 :(得分:1)
以下代码将输出一个带有提取列的数据框。我放入tolower()函数将示例更改为所有小写字母。如果要“模糊”匹配,则可能需要查看正则表达式。 https://stringr.tidyverse.org/articles/regular-expressions.html
example <- structure(list(df = c("Tsilver flash mirror", "E:~ ADD FLASH FRONT MI",
"E:~", "E##T Color: G 15#3; MC", "E:~ ## PLEASE USE 8 BA", "E:~ ## blue flash ##",
"E:~ ## Silver Mirror #", "Ssilver mirror", "E:~ ## Treatment: Fee-",
"E:~Further Instruction", "E:~ ## FORREST GRAY Xp", "ESILVER",
"EGOLD")), class = "data.frame", row.names = c("1", "2", "3",
"4", "5", "6", "7", "8", "9", "10", "11", "12", "13"))
color_list <- c("gray", "brown", "green", "plum", "mist", "forest", "sienna", "grape", "ruby", "emerald", "copper",
"silver", "gold", "blue")
example %>%
mutate(extract = str_extract(tolower(df), paste(color_list, collapse = "|")))