从没有语料库的数据框中提取子词列表

时间:2013-12-12 09:57:25

标签: regex r dataframe

实际上我想在数据框中提取一些子词列表,我知道我们可以通过语料库提取但我不想做那些不必要的事情。我最后使用匹配以及 grep 但问题是匹配不能用于其他精确匹配而grep不能用于多个单词。例如。

 a=sample(c("Client","offshor","V1fax","12mobile"),10)
 z=data.frame(a)
 z
          a
1     V1fax
2     V1fax
3  12mobile
4  12mobile
5     V1fax
6     clint
7   offshor
8     clint
9     clint
10 12mobile

d=z[is.na(match(tolower(z[,1]),c("fax","mobile","except","talwade"))),]

grep(c("fax","mobile","except","talwade"),tolower(z[,1]))
    [1] 1 2 5
Warning message:
In grep(c("fax", "mobile", "except", "talwade"  :
  argument 'pattern' has length > 1 and only the first element will be used

希望o / p为

z
       a
1     clint
2   offshor
3     clint
4     clint

正如预期的那样提取子词列表的任何有效方法。谢谢。

2 个答案:

答案 0 :(得分:2)

您可以使用grep执行此操作,只需使用OR的正则表达式|运算符...

grep(  paste( c("fax","mobile","except","talwade") , collapse = "|" ) , tolower(z[,1]) )
# [1] 1 2 3 4 5 10


#  The pattern...
paste( c("fax","mobile","except","talwade") , collapse = "|" )
# [1] "fax|mobile|except|talwade"

答案 1 :(得分:1)

这将比Simon的解决方案慢一点,但它可以访问更多数据进行分析。您可以使用sapply返回匹配矩阵:

patterns  <- c("fax","mobile","except","talwade")
match.mat <- sapply(patterns, grepl, z$a)
rownames(match.mat) <- z$a

#            fax mobile except talwade
# V1fax     TRUE  FALSE  FALSE   FALSE
# V1fax     TRUE  FALSE  FALSE   FALSE
# 12mobile FALSE   TRUE  FALSE   FALSE
# 12mobile FALSE   TRUE  FALSE   FALSE
# V1fax     TRUE  FALSE  FALSE   FALSE
# clint    FALSE  FALSE  FALSE   FALSE
# offshor  FALSE  FALSE  FALSE   FALSE
# clint    FALSE  FALSE  FALSE   FALSE
# clint    FALSE  FALSE  FALSE   FALSE
# 12mobile FALSE   TRUE  FALSE   FALSE

使用该矩阵,您可以回答很多事情:

元素至少有一个匹配:

rowSums(match.mat) > 0
#    V1fax    V1fax 12mobile 12mobile    V1fax    clint  offshor    clint    clint 12mobile 
#     TRUE     TRUE     TRUE     TRUE     TRUE    FALSE    FALSE    FALSE    FALSE     TRUE 

哪些:

which(rowSums(match.mat) > 0)
#    V1fax    V1fax 12mobile 12mobile    V1fax 12mobile 
#        1        2        3        4        5       10 

对于某个特定单词,匹配的是哪种模式,反之亦然:

which(match.mat["12mobile", ])
which(match.mat[, "fax"])