本文介绍了在 R 中使用 grepl 匹配字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个框架数据testData"如下:

I have a frame data "testData" as follows:

id     content
 1     I came from China
 2     I came from America
 3     I came from Canada
 4     I came from Japan
 5     I came from Mars

而且我还有另一个框架数据addr"如下:

And I also have another frame data "addr" as follows:

id   addr
 1   America
 2   Canada
 3   China
 4   Japan

那么我如何使用 greplsapply 或 R 中的任何其他有用的函数来生成如下数据:

Then how can I use grepl, sapply or any other useful function in R to generate data into as follows:

id   content               addr
 1   I came from China     China
 2   I came from America   America
 3   I came from Canada    Canada
 4   I came from Japan     Japan
 5   I came from Mars      Mars

推荐答案

这样做的诀窍:

vec = addr$addr

testData$addr = apply(testData, 1, function(u){
    bool = sapply(vec, function(x) grepl(x, u[['content']]))
    if(any(bool)) vec[bool] else NA
})

这篇关于在 R 中使用 grepl 匹配字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 05:35