删除以{?[ in R]开头的行

bprjcwpo  于 2023-11-14  发布在  其他
关注(0)|答案(3)|浏览(129)

我想删除df中所有以[,{ or?

Value   Phenotype 
    55     [REVERSE223, some randome words   
    22     GENJJS, a string with ? in the middle, not removed
    33     {REVERSE456, this can be whatever
    44     ?GENJKI, a not so long string

字符串

Value   Phenotype 
    22     GENJJS, a string with ? in the middle, not removed


我试

df <- df[- grep("{", df$Name),]


我计划对“?”和“[”重复该命令,但这三个字符似乎很复杂,我不知道如何解决它。
希望有人能帮忙。
谢谢你,谢谢

pw9qyyiw

pw9qyyiw1#

你可以在[中使用put [{?来修饰它们,在grep中使用set invert=TRUE。非常重要的一点是使用^来指示字符串的开始。

> df[grep("^[[{?]", df$Phenotype, invert = TRUE), ]
  Value                                          Phenotype
2    22 GENJJS, a string with ? in the middle, not removed

字符串
其他组合:

df[-grep("^[[{?]", df$Phenotype), ]
df[!grepl("^[[{?]", df$Phenotype), ]


或多个通用

> df[grepl("^\\w", df$Phenotype), ]
  Value                                          Phenotype
2    22 GENJJS, a string with ? in the middle, not removed

wbgh16ku

wbgh16ku2#

所以你遇到了一个问题,你决定用正则表达式来解决它。现在你有两个问题了。
有时候,放弃正则表达式而使用简单的substr会更容易。这里可能是最简单的:

example <- data.frame(id = 1:4, Pheno = c("[REVERSE223, some randome words",
                                          "GENJJS, a string with ? in the middle, not removed",
                                          "{REVERSE456, this can be whatever",
                                          "?GENJKI, a not so long string"))
forbidden <- c("[", "{", "?")
                                          
drop.rows <- which(substr(example$Pheno, 1, 1) %in% forbidden)

example.clean <- example[-drop.rows,]
print(example.clean)

字符串

nue99wik

nue99wik3#

你可以用这些特殊字符定义一个字符类,注意[{?都是正则表达式的元字符;但是,在字符类中,只有[需要被转义(\\[)。通过在字符类前面添加锚^,可以Assert这些字符必须出现在字符串的开头:

library(dplyr)
library(stringr)
example %>%
    filter(!str_detect(Pheno, "^[\\[{?]")
  id                                              Pheno
1  2 GENJJS, a string with ? in the middle, not removed

字符串
数据类型:

example <- data.frame(id = 1:4, Pheno = c("[REVERSE223, some randome words",
                                          "GENJJS, a string with ? in the middle, not removed",
                                          "{REVERSE456, this can be whatever",
                                          "?GENJKI, a not so long string"))

相关问题