【问题标题】:remove rows containing matching numeric strings [closed]删除包含匹配数字字符串的行 [关闭]
【发布时间】:2017-12-24 19:31:22
【问题描述】:

我有一个包含 3 列的数据框:

df

A             B               C
round1    test1        testing1
round1    test1        testing2
round1    test1        testing3
round1    test1        testing4
round1    test1        testing5
round2    test2        testing1
round2    test2        testing2
round2    test2        testing3
round2    test2        testing4
round2    test2        testing5
.
.
.
.
.
round100  test30       testing30
round100  test30       testing31

如何删除BC列字符串中数值匹配的行?

【问题讨论】:

    标签: r dplyr gsub


    【解决方案1】:

    只需提取数字部分并进行比较。

    NumB = sub("\\D+(\\d+).*", "\\1", DAT$B)
    NumC = sub("\\D+(\\d+).*", "\\1", DAT$C)
    DAT = DAT[NumB != NumC,]
    

    数据

    DAT = read.table(text="A       B     C
    round1    test1        testing1
    round1    test1        testing2
    round1    test1        testing3
    round1    test1        testing4
    round1    test1        testing5
    round2    test2        testing1
    round2    test2        testing2
    round2    test2        testing3
    round2    test2        testing4
    round2    test2        testing5",
    header=TRUE, stringsAsFactors = FALSE)
    

    【讨论】:

      【解决方案2】:

      用空字符串替换非数字 "\\D" 并比较剩下的内容:

      subset(DF, gsub("\\D", "", B) != gsub("\\D", "", C))
      

      给出这个输入DF在下面的注释中重复显示:

                A      B         C
      2    round1  test1  testing2
      3    round1  test1  testing3
      4    round1  test1  testing4
      5    round1  test1  testing5
      6    round2  test2  testing1
      8    round2  test2  testing3
      9    round2  test2  testing4
      10   round2  test2  testing5
      12 round100 test30 testing31
      

      注意

      可重现形式的输入是:

      Lines <- "
      A             B               C
      round1    test1        testing1
      round1    test1        testing2
      round1    test1        testing3
      round1    test1        testing4
      round1    test1        testing5
      round2    test2        testing1
      round2    test2        testing2
      round2    test2        testing3
      round2    test2        testing4
      round2    test2        testing5
      round100  test30       testing30
      round100  test30       testing31"
      DF <- read.table(text = Lines, header = TRUE)
      

      【讨论】:

        猜你喜欢
        • 2022-06-10
        • 1970-01-01
        • 2013-02-21
        • 2014-04-16
        • 1970-01-01
        • 2019-04-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多