简体   繁体   English

R 从字符串中删除(NA)

[英]R remove (NA) from a string

I have我有

"this is an example (NA)"

and would like to have "this is an example"并希望有"this is an example"

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

does not work.不起作用。

I have tried gsub我试过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 :另一种可能的解决方案,基于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您应该启用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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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