Reputation: 111
I'm trying to do the delete rows that containing a specific character
This is an example of what I'm trying to do. I'm trying to keep IDs which does not have B
in them
input
IDs
WW-111
WW-112
WW2_111B
WW2_112B
WW_1234
2210B
2222B
I'm looking for output as this
IDs
WW-111
WW-112
WW_1234
What is the right approach to do that?
Upvotes: 1
Views: 82
Reputation: 59
An amateur method would be:
Accept strings->accept or define character that shouldnt be in string->run loop checking each character of string, take a counter variable, if variable =0, print string.
Upvotes: 0
Reputation: 887213
We can also use the invert
and value
arguments in grep
grep("B$", x, invert = TRUE, value = TRUE)
#[1] "WW-111" "WW-112" "WW_1234"
x <- c("WW-111","WW-112","WW2_111B","WW2_112B","WW_1234","2210B","2222B")
Upvotes: 1
Reputation: 39667
In base you can use grepl
and negate the hits of B
like:
x[!grepl("B", x)]
[1] "WW-111" "WW-112" "WW_1234"
Data:
x <- c("WW-111","WW-112","WW2_111B","WW2_112B","WW_1234","2210B","2222B")
Upvotes: 3
Reputation: 4233
If you want to keep things simple, you can use stringr::str_detect
:
x <- c("A", "AB", "BB", "CC", "D", "DBD")
x[!stringr::str_detect(x, "B")]
Output
"A" "CC" "D"
Upvotes: 2
Reputation: 337
Try ^[^B]+$
Breaking it down, this means
^ start of the string
[^B] any character except those in the brackets
+ at least one of the previous characters
$ end of the string
Upvotes: 1