【问题标题】:Using grepl in R to match string在 R 中使用 grepl 匹配字符串
【发布时间】:2015-01-30 06:26:39
【问题描述】:

我有一个帧数据“testData”如下:

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”如下:

id   addr
 1   America
 2   Canada
 3   China
 4   Japan

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

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

【问题讨论】:

  • 我的 testData 是用户发布的推文。所以它们不像这个样本那么整洁。我只能使用 grep 或 grepl 来查找每个 testData.content 是否包含我认为的 addr 中的任何单词。

标签: r sapply grepl


【解决方案1】:

这就是诀窍:

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
})

【讨论】:

  • 抱歉,我不能使用 gsub。因为真实的数据不是那么整齐。它们是真人发布的推特。我想看看这些推特是否有一些特定的词。如果任何 twitter 有任何我想找到的特定单词。那么这些词将被添加到推特,或者没有
【解决方案2】:

看起来您只想复制该列并删除“我来自”

testData$addr <- gsub("I came from ", testData$content)

【讨论】:

  • 对不起,我可能没有说清楚。在我的真实数据中,可能会有各种文本。例如“是中国”、“他来自中国,但不是真实的”等等。无论如何,我不能使用 gsub 或 regex 来做到这一点。我只能使用 grepl 来查找 testData 的每一行是否包含 addr(或另一个字符串向量)中的任何单词。如果是,则该单词将被添加到行中,或者不添加。
  • 那么您应该在原始问题中添加类似的示例。为什么不能使用正则表达式?这是作业题吗?
  • 对不起,我举的例子不是很好。由于我想在文本中搜索的单词尚未确定。并且 testData$content 很复杂。所以我想我只能使用 grepl 来搜索文本中的单词。这不是一个家庭作业问题。我在处理另一个任务时遇到了它。
【解决方案3】:

这是使用一些tidyverse 函数的粗略解决方案:

df1 <- read.table(text = "id     content
 1     'it is China'
 2     'She is in America now'
 3     'Canada is over there'
 4     'He comes from Japan'
 5     'I came from Mars'", header = TRUE, stringsAsFactors = FALSE)

df2 = read.table(text = "id   addr
 1   America
 2   Canada
 3   China
 4   Japan
 5   Mars", header = TRUE, stringsAsFactors = FALSE)

library(tidyverse)
crossing(df1, df2 %>% select(addr)) %>% # this creates a data frame of every possible content and add combination
  rowwise() %>% 
  filter(str_detect(content, add)) # str_detect is the same as grepl, though the arguments are reversed. This filters to only observations where addr is in content.

# A tibble: 5 x 3
     id content               addr   
  <int> <chr>                 <chr>  
1     1 it is China           China  
2     2 She is in America now America
3     3 Canada is over there  Canada 
4     4 He comes from Japan   Japan  
5     5 I came from Mars      Mars

【讨论】:

    猜你喜欢
    • 2022-01-17
    • 2013-03-16
    • 1970-01-01
    • 2020-01-26
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多