Rameez Shaik Rameez Shaik - 29 days ago 12
R Question

How to remove certain character from a vector in R

I have a vector, for example,

c(21,34,"99*",56,"90*", "45*")
. I need to clean the data using R by transforming this into a vector without the extra
*
. The result in this example should be
c(21,34,99,56,90,45)
.

Answer Source

We can use sub to remove the * by specifying fixed = TRUE as it is a metacharacter that denotes zero or more characters. In addition to fixed = TRUE, it can be escaped (\\*) or place inside square brackets ([*]) to get the literal meaning of *

as.numeric( sub("*", "", v1, fixed = TRUE))
#[1] 21 34 99 56 90 45

A convenient function would be parse_number from readr

readr::parse_number(v1)
#[1] 21 34 99 56 90 45

data

v1 <- c(21,34,"99*",56,"90*", "45*")