2

我有一个向量,我想针对数据帧的每一行检查每个元素。它涉及一个 grep 函数,因为要检查的元素隐藏在其他文本中。

在这个论坛的帮助下,我得到了这个代码:

    mat=data.frame(par=c('long A story','C story', 'blabla D'),val=1:3) 
    vec=c('Z','D','A')
    mat$label <- NA
    for (x in vec){
       is.match <- lapply(mat$par,function(y) grep(x, y))
       mat$label[which(is.match > 0)] <- x
    }

问题是执行需要几分钟。有没有办法对此进行矢量化?

4

1 回答 1

3

我假设您只想要每种情况下的第一个匹配项:

which.matches <- grep("[ZDA]", mat$par)
what.matches <- regmatches(mat$par, regexpr("[ZDA]", mat$par))

mat$label[which.matches] <- what.matches
mat

           par val label
1 long A story   1     A
2      C story   2  <NA>
3     blabla D   3     D

编辑:基准测试

Unit: microseconds
           expr     min       lq  median       uq      max
1   answer(mat) 185.338 194.0925 199.073 209.1850  898.919
2 question(mat) 672.227 693.9610 708.601 725.6555 1457.046

编辑2:

正如@mrdwab 建议的那样,这实际上可以用作单线:

mat$label[grep("[ZDA]", mat$par)] <- regmatches(mat$par, regexpr("[ZDA]", mat$par))
于 2012-08-01T09:01:33.020 回答