How to use str_detect() to select rows and then create a new variable based on the pattern it is matched with?
我有一个几十万行的数据集。以下是它们外观的示例。
1 2 3 4 5 6 7 8 | X user_id screen_name name location 1 1 1.732895e+09 DROPPSScience DROPPS Consortium 2 2 1.172266e+18 Lamy40283167 Alex lamy precious Washington, USA 3 3 3.773702e+08 cdockjr Calvin Wilborn Alabama, USA 4 4 7.040063e+07 xmtl2 Felicio 5 5 3.929519e+08 DeleceWrites Delece Smith-Barrow Washington, DC 6 6 1.130459e+18 evabrooke_26 Eva 7 7 1.067302e+08 MitchellHortert Mitchell R. Hortert Pittsburgh,PA |
我在https://github.com/jasonong/List-of-US-States/blob/master/states.csv
中找到了第二个数据集
我正在尝试使用str_detect()查找" location"列和states.csv文件中任一列之间的任何匹配项。然后,我想创建一个新变量,为每个观察值存储匹配的模式。
到目前为止,我已经尝试使用
1 2 | data.set %>% filter(str_detect(location, paste(states$State) |
这将返回一些匹配项,但忽略许多观察并给出警告
1 2 3 | Warning message: In stri_detect_regex(string, pattern, negate = negate, opts_regex = opts(pattern)) : longer object length is not a multiple of shorter object length |
states $ State是一个因子变量,每个状态和DC具有51个级别。
是什么导致此警告,但匹配很少,但在一定程度上起作用?
最后,我如何基于匹配的发生时间创建一个新变量,将匹配模式放入新变量中?
如果"位置"和"状态"的长度不同,则可以选择使用
1 2 3 4 | library(stringr) library(dplyr) data.set %>% filter(str_detect(location, paste(states$State, collapse ="|"))) |
因为我们已经在使用
1 2 | data.set %>% filter(str_detect(location, str_c(states$State, collapse ="|"))) |
或者如@HanselPalencia所述,如果"状态"中存在混淆,请使用"缩写"列进行模式检测
1 2 | data.set %>% filter(str_detect(location, str_c(states$Abbreviation, collapse ="|"))) |