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

后端 未结 4 1007
北荒
北荒 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: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
    

提交回复
热议问题