Using grep in R to delete rows from a data.frame

后端 未结 4 996
北荒
北荒 2020-12-30 07:34

I have a dataframe such as this one:

    d <- data.frame(cbind(x=1, y=1:10,    z=c(\"apple\",\"pear\",\"banana\",\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\"         


        
相关标签:
4条回答
  • 2020-12-30 08:14

    For completeness, since R 3.3.0, grep and friends come with an invert argument:

    new_d <- d[grep("K", d$z, invert = TRUE)]
    
    0 讨论(0)
  • 2020-12-30 08:19

    You want to use grepl in this case, e.g., new_d <- d[! grepl("K",d$z),].

    0 讨论(0)
  • 2020-12-30 08:34

    Here's your problem:

    > grep("K",c("apple","pear","banana","A","B","C","D","E","F","G"))
    integer(0)
    

    Try grepl() instead:

    d[!grepl("K",d$z),]
    

    This works because the negated logical vector has an entry for every row:

    > grepl("K",d$z)
     [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
    > !grepl("K",d$z)
     [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
    
    0 讨论(0)
  • 2020-12-30 08:38

    You can use TRUE/FALSE subsetting instead of numeric.

    grepl is like grep, but it returns a logical vector. Negation works with it.

     d[!grepl("K",d$z),]
       x  y      z
    1  1  1  apple
    2  1  2   pear
    3  1  3 banana
    4  1  4      A
    5  1  5      B
    6  1  6      C
    7  1  7      D
    8  1  8      E
    9  1  9      F
    10 1 10      G
    
    0 讨论(0)
提交回复
热议问题