简体   繁体   中英

want to remove certain value from the vector in R

I have vector in the below form:

a<-

[1] "[1]"                "\"0\""              "\"0\""              "\"0\""              "\"0\""              "[5]"                "\"0\""              "\"0\""              "\"0\""              "\"0\""             
[11] "[9]"                "\"0\""              "\"0\""              "\"0\""              "\"0\""              "[13]"               "\"0\""              "\"0\""              "\"0\""              "\"0\"" 

I want to remove all the numbers "[1]","[5]","[11]","[15]"...."[1500]" so on using gsub or regex in R. I have given a try below:

remove<- gsub("[0:9]", a)

But getting following error:

Error in gsub("[0:9]", a) : argument "x" is missing, with no default

Thanks in advance!

Note that gsub only removes text inside character vector items, it does not remove the items themselves. In this case, you need a grep -like solution.

You may use a simple pattern to identify those items:

^\[\d+]$

See the regex demo .

Details

  • ^ - start of string
  • \\[ - a [ char
  • \\d+ - 1+ digits
  • ] - a literal ]
  • $ - end of string.

Then, use it with grep command with invert=TRUE option to only keep the items that do not match this regex, and value=TRUE to get the values rather than indices.

See the R demo :

> a <- c("[1]", "\"0\"")
> grep("^\\[\\d+]$", a, invert=TRUE, value=TRUE)
[1] "\"0\""

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