简体   繁体   中英

R remove (NA) from a string

I have

"this is an example (NA)"

and would like to have "this is an example"

gsub("(NA)", "", "this is an example (NA)")

does not work.

I have tried gsub

gsub("(NA)", "", "this is an example (NA)")
[1] "this is an example ()"

You can try:

"this is an example (NA)" -> x
gsub('\\(NA)', '', x)

Another possible solution, based on stringr :

library(stringr)

string <- "this is an example (NA)"
str_remove_all(string, "\\s*\\(NA\\)\\s*")

#> [1] "this is an example"

You should enable fixed = TRUE

> gsub("(NA)", "", "this is an example (NA)", fixed = TRUE)
[1] "this is an example "
string <- "this is an example (NA)"
gsub(' \\(NA\\)', '', string)
[1] "this is an example"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM