【问题标题】:R - looping across 2 objectsR - 遍历 2 个对象
【发布时间】:2016-01-13 15:28:25
【问题描述】:

我正在尝试做一些相当简单的事情(我认为),但我无法理解它。我正在尝试编写一个循环来检查数据框中的字符变量是否包含任何特定的子字符串列表,并将相应的值分配给虚拟变量。

所以,想象一个 data.frame,n=2000,有一个变量 data.frame$text。此外,我有一个字符向量,其中包含我想要为data.frame$text 发送文本的所有子字符串。我们就叫它hillary_exists

hillary_exists <- c("Hilary Clinton", "hilary clinton","hilaryclinton", "hillaryclinton", "HilaryClinton",
                    "HillaryClinton","Hillary Clinton", "Hillary Rodham Clinton", "Hillary", "Hilary", "#Hillary2016", "#ImWithHer",
                    "Hillary2016", "hillary", "hilary", "Clinton 2016", "Clinton", "Secretary of State Clinton", 
                    "Senator Clinton", "Hilary Rodham", "Hilary Rodham Clinton", "Hilary Rodham-Clinton", "Hillary Rodham-Clinton")

现在,我希望我的循环测试data.frame$text 的每一行是否存在hillary_exists 的每个元素,如果它们中的任何一个是TRUE,则生成1 的新值对于变量 data.frame$hillary_mention 。这是我尝试过的:

for(i in hillary_exists){
  if(grepl(hillary_exists[i], data.frame$text)){
    data.frame$hillary_mention <- 1
  } else {
    data.frame$hillary_mention <- 0 }
}

但显然我缺少data.frame$text 元素的i 组件,但我不知道如何解决它。

任何帮助将不胜感激!谢谢

【问题讨论】:

  • 您好 Avinash,感谢您的评论,您能否详细说明一下?据我所知,这几乎就是我所做的,不是吗?
  • 这样,data.frame$hillary_mention[i] &lt;- 1
  • data.frame$hillary_mention &lt;- sapply(data.frame$text,function(s) any(grepl(s,hillary_exists))) 怎么样?
  • @brittenb,也许你是对的,但我不清楚算法的期望行为是什么。 @nikUoM,说,我们有hillary_exist &lt;- c('ab','bc','cd')d &lt;- data.frame(text=c(letters[1:5],'ab','de'));在这种情况下,预期的输出是什么?
  • 在我看来,这段代码可能会给出正确的解决方案:data.frame$hillary_mention &lt;- match(data.frame$text,hillary_exists,nomatch=0) 。更好的是:data.frame$hillary_mention &lt;- data.frame$text %in% hillary_exists

标签: regex r loops for-loop grepl


【解决方案1】:

我们可以用来使其工作的一种方法是将hillary_exists 转换为正则表达式:hillary_regex &lt;- paste(hillary_exists, collapse = "|")。从本质上讲,这只是将您的所有条款转化为一个大的 OR 语句。这会自动为我们处理其中一个循环。接下来,我们使用sapply 循环我们的文本列data.frame$text

data.frame$hillary_mention <- sapply(data.frame$text, function(s) grepl(hillary_regex, s, ignore.case = TRUE))

这里最好使用ignore.case = TRUE,因为文本中可能会出现hillary_exists 中未提及的内容,例如“hIllary cLinTon”。

【讨论】:

    猜你喜欢
    • 2016-09-26
    • 2019-02-12
    • 2020-01-28
    • 2014-08-17
    • 1970-01-01
    • 1970-01-01
    • 2013-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多