使用用于使用data.tables进行匹配的字符串填充列

时间:2018-11-05 06:40:13

标签: r data.table

我在这里创建两个data.tables

library(data.table)
library(stringr)

mydt <- data.table(summary=c("Denial of Service vulnerability in BIND 8 Releases",
                          "Denial of Service vulnerabilities in BIND 4.9 and BIND 8",
                          "Buffer overflow in NFS mountd gives root access",
                          "Buffer overflow in statd allows root privileges.",
                          "Cross-site scripting (XSS) vulnerability in Open-Xchange",
                          "SQL injection vulnerability in mod_accounting.c in the"),
                    wascname=c(NA,NA,NA,NA,NA,"SQL Injection"))

 wasc <- data.table(wascname=c("Abuse of Functionality",
                              "Cross-Site Scripting",
                              "Buffer Overflow",
                              "Denial of Service",
                              "SQL Injection"))

mydt的输出

enter image description here

在这里,我使用用于匹配的字符串填充列的解决方案。

mydt$wascname <-
   sapply(1:nrow(mydt), function(x)
     ifelse(
       is.na(mydt$wascname[x]),
       wasc$wascname[str_detect(mydt$summary[x],
                                     regex(wasc$wascname, ignore_case = TRUE))],
       mydt$wascname[x]
     ))

输出

enter image description here

我想使用data.table形式DT[i, j, by]获得相同的结果。我尝试了其他解决方案,但无法使用DT表单来工作。

我在睡觉时对此进行了更多思考,并重新编写了工作以实现DT[i, j, by]形式。请在下面查看解决方法,该操作可以为我提供所需的输出:

 mydt[ , wascname:= sapply(1:nrow(mydt),function(x)
   ifelse(is.na(wascname[x]),
          wasc$wascname[str_detect(summary[x],
                                   regex(wasc$wascname, ignore_case = TRUE))],
          wascname[x]))]

1 个答案:

答案 0 :(得分:0)

library(stringr)
library(tidyverse)

df2<- mydt %>%
  mutate(match = str_extract(tolower(mydt$summary), str_c(tolower(wasc), collapse = "|")))

这将提供您想要的输出。

在这种情况下,带有tidyverse的

stringr将起作用。

确保wasc已保存为列表

相关问题