从数据框中提取子词列表,无需语料库。

3

实际上,我想从数据框中提取一些子词列表,我知道我们可以通过语料库提取,但我不想做那些不必要的事情。首先我使用了matchgrep,但问题是match只能用于精确匹配,而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

希望输出结果是:

z
       a
1     clint
2   offshor
3     clint
4     clint

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

2个回答

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
这种方法比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 ones:”(哪些)
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"])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接