【问题标题】:Find in R elements in same text vector that contain two substrings [duplicate]在包含两个子字符串的同一文本向量中查找 R 元素[重复]
【发布时间】:2020-07-04 13:50:30
【问题描述】:

我有一个包含五个元素的文本向量,名为 text2。它是一个实际数据集的样本,包含 1,800 多行和多列。

我查看了 stackoverflow 中的其他代码解决方案,但找不到匹配项。

输入

text2 <- c("Ian Desmond hits an inside-the-park home run (8) on a line drive down the right-field line. Brendan Rodgers scores. Tony Wolters scores." , "Ian Desmond lines out sharply to center fielder Jason Heyward.", "Ian Desmond hits a grand slam (9) to right center field. Charlie Blackmon scores. Trevor Story scores. David Dahl scores.", "Ian Desmond homers (12) on a fly ball to center field. Daniel Murphy scores.", "Wild pitch by pitcher Jake Faria. Sam Hilliard scores.")

输出 我想知道 text2 中的哪些元素同时包含“Wild pitch”和“scores”。我想要计数和元素编号。例如, 在 text2 中只有一个元素(最后一个)是匹配的。因此,输出将包含计数 (1) 和元素编号 (5)。

代码已尝试 str_detect(text2, ("Wild pitch|scores"))

【问题讨论】:

    标签: r string stringr


    【解决方案1】:

    您在正确的轨道上,但是 str_detect(text2, ("Wild pitch|scores")) 会告诉您 Wild pitch OR 分数是否包含在 text2 中。这将为您提供所需的输出:

    ind <- str_detect(text2, "Wild pitch") & str_detect(text2, "scores")
    count <- sum(ind)
    count 
    # 1
    pos <- which(ind)
    pos 
    # 5
    

    【讨论】:

      【解决方案2】:

      单行 dplyr 解决方案

      require(dplyr)
      require(tidyr)
      
      text2 %>% 
        as_tibble() %>% 
        mutate(WP = str_detect(text2,"Wild pitch"),
               S = str_detect(text2,"scores")) %>% 
        summarise(count=sum(WP==T & S==T),
                  position=list(which(WP==T & S==T))) %>% 
        unnest(cols=c(position))
      

      这给出了:

      # A tibble: 1 x 2
        count position
        <int>    <int>
      1     1        5
      

      【讨论】:

      • 当我运行你的代码时,我得到了这个错误:错误 in unnest(., cols = c(position)) : could not find function "unnest"
      • 因为它在tidyr 包中,所以我编辑了我的帖子;)
      • summarise(count=sum(WP==T &amp; S==T) 中的“T”值从何而来? WP 和 S 等于什么?
      • T 表示 TRUE,因此当句子中包含 "Wild pitch""scores" 时,count=sum(WP==T &amp; S==T) 将元素数相加。
      【解决方案3】:

      您可以使用pattern

      pattern <- 'Wild pitch.*scores|scores.*Wild pitch'
      

      要查找位置,您可以使用grep

      grep(pattern, text2)
      #[1] 5
      

      对于计数,您可以获得greplength

      length(grep(pattern, text2))
      #Can also use grepl with sum
      #sum(grepl(pattern, text2))
      #[1] 1
      

      【讨论】:

        【解决方案4】:

        具有正向前瞻性的单线解决方案:

        res <- c(length(grep("(?=Wild pitch).*scores", text2, perl = T)), 
                 grep("(?=Wild pitch).*scores", text2, perl = T))
        
        res
        [1] 1 5
        

        如果Wild pitchscores的共现顺序是可变的,那么使用这个模式:

        "(?=Wild pitch)*(?=scores).*"
        

        【讨论】:

          猜你喜欢
          • 2015-05-08
          • 2016-03-03
          • 1970-01-01
          • 2018-11-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-07-08
          相关资源
          最近更新 更多