选择列表中包含R中给定表达式的所有字符串

时间:2018-12-05 08:34:03

标签: r regex text data-analysis

我正在将犯罪统计.csv文件读取到名为crimes的变量中。新的数据框犯罪包含一个标题为Text_General_Code的列,该列简要描述了所犯的犯罪。我想找出入室盗窃和抢劫在犯罪中所占的百分比。我正在使用以下表达式来计算百分比:

percentage <- (sum(str_detect(crimes$Text_General_Code, "burglary")) + sum(str_detect(crimes$Text_General_Code, "robbery")))/length(crimes$Text_General_Code)

我非常确定我所做的一切都很好,但是百分比始终显示为0,如果您查看.csv文件,则情况并非如此。我不确定这是什么错误,也许是我使用的正则表达式?

.csv输入的示例 1/2

2/2

dput(crimes[1:10],)结果:

structure(list(Dc_Dist = c(15L, 16L, 17L, 16L, 25L, 17L, 8L, 
24L, 2L, 19L), Psa = c("1", "F", "L", "F", "G", "Q", "N", "2", 
"D", "2"), Year = c("2011", "2006", "2006", "2006", "2008", "2006", 
"2009", "2015", "2007", "2014"), Month = c("05", "08", "10", 
"06", "02", "12", "06", "09", "07", "05"), Day = c("15", "22", 
"23", "01", "14", "30", "04", "29", "31", "24"), Hour = c("16", 
"00", "06", "07", "10", "12", "15", "16", "23", "23"), Minute = c("58", 
"18", "50", "34", "39", "59", "23", "27", "09", "05"), Second = c("00", 
"00", "00", "00", "00", "00", "00", "00", "00", "00"), `-` = c(NA_character_, 
NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, 
NA_character_, NA_character_, NA_character_, NA_character_), 
    Dc_Key = c(201115048144, 200616039763, 200617055978, 200616024616, 
    200825015369, 200617067285, 200908024218, 201524093777, 200702051812, 
    201419045553), Location_Block = c("4300 BLOCK CLOUD ST", 
    "3800 BLOCK SPRING GARDEN ST", "1600 BLOCK S MARSTON ST", 
    "600 BLOCK N 39TH ST  / 3900 WALLACE ST", "2800 BLOCK N HOWARD ST", 
    "1200 BLOCK S 28TH ST", "9200 BLOCK ASHTON RD", "3000 BLOCK ELLA ST", 
    "7700 BLOCK CASTOR AV", "200 BLOCK N 59TH ST"), UCR_General = c(1400L, 
    2600L, 2600L, 600L, 700L, 700L, 400L, 1800L, 2600L, 2600L
    ), Text_General_Code = c("Vandalism/Criminal Mischief", "All Other Offenses", 
    "All Other Offenses", "Thefts", "Recovered Stolen Motor Vehicle", 
    "Motor Vehicle Theft", "Aggravated Assault No Firearm", "Narcotic / Drug Law Violations", 
    "All Other Offenses", "All Other Offenses"), Police_Districts = c(11L, 
    12L, 13L, NA, 18L, 13L, 7L, 17L, 2L, 15L), Lon = c(-75.085466, 
    -75.197275, -75.190926, NA, -75.131325, -75.190218, -75.020848, 
    -75.127396, -75.060318, -75.238174), Lat = c(40.010122, 39.962331, 
    39.932177, NA, 39.993706, 39.937967, 40.064338, 39.995156, 
    40.057514, 39.964831)), .Names = c("Dc_Dist", "Psa", "Year", 
"Month", "Day", "Hour", "Minute", "Second", "-", "Dc_Key", "Location_Block", 
"UCR_General", "Text_General_Code", "Police_Districts", "Lon", 
"Lat"), row.names = c(NA, 10L), class = "data.frame")

1 个答案:

答案 0 :(得分:0)

正则表达式默认情况下区分大小写:

percentage <- (sum(str_detect(crimes$Text_General_Code, "(?i)burglary")) + sum(str_detect(crimes$Text_General_Code, "(?i)robbery")))/length(crimes$Text_General_Code)

使用全局标志"(?i)"来使搜索不区分大小写,从而使

模式= "aaaa"可以与"AaAa", "Aaaa", "aaAa" .... etc匹配