【问题标题】:string split and conditional paste字符串拆分和条件粘贴
【发布时间】:2016-02-19 19:57:44
【问题描述】:

我正在处理如下数据帧

        id            Comments
        1             The apple fell far from the mango tree
        2             I was born under a mango tree and a wandering star      
        3             Mules are made for packing and Mangoes for eating

我对 mango 这个词之前的 4 个词和之后的 4 个词感兴趣,包括 mango 这个词。

最终的数据集将如下所示。

        id            Comments
        1             far from the mango tree
        2             born under a mango tree and a      
        3             for packing and Mangoes for eating

这是测试可重现数据集

df <- read.table(text="Id,Comment
 1,The apple fell far from the mango tree
                 2,I was born under a mango tree and a wandering star      
                 3,Mules are made for packing and Mangoes for eating", header=T, sep=",")

关于这个非常受欢迎的任何见解

【问题讨论】:

  • 前后没有4个字的情况怎么办?您要排除这些情况吗?
  • 能有多个芒果吗
  • @bdeonovic 示例中似乎涵盖了这种情况,例如,id=1 后面只有一个单词。

标签: r string gsub stringr grepl


【解决方案1】:

我使用了非常好的stringi 包和正则表达式技术:

library(stringi)
apply(df,1, function(myrow){
   stri_match_all_regex(myrow[2], "(\\p{L}+\\p{Z}){0,3}(mango\\p{L}*|Mango\\p{L}*)(\\p{Z}\\p{L}+){0,3}")[[1]][1,1]
   })

所以我在mango ((\\p{L}+\\p{Z}){0,3}) 之前得到了 0 到 3 个单词,在那个芒果或 Mango 后面加上了额外的字母 ((mango\\p{L}*|Mango\\p{L}*)) 之后又从 0 到 3 个单词 ((\\p{Z}\\p{L}+){0,3} )

\p{Z} 是空格,\p{L} 是字母。

【讨论】:

    【解决方案2】:

    这似乎有效:

    sapply(
      strsplit(as.character(df$Comment), " "),
      function(x){
        w = grep("[m|M]ango", x)[1]
        paste(x[ seq(max(1,w-3), min(length(x),w+3)) ], collapse=" ") 
      }
    )
    # [1] "far from the mango tree"           
    # [2] "born under a mango tree and a"     
    # [3] "for packing and Mangoes for eating"
    

    grep(...)[1] 表示只使用第一个芒果匹配。

    【讨论】:

    • 感谢 bud,如果没有 N 或 Missin 数据,这项工作会很好。如果有的话,它就崩溃了。
    • @KingFrazier 哎呀,没想到它会崩溃任何东西。很高兴你得到了一些有用的东西
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-03
    • 1970-01-01
    相关资源
    最近更新 更多