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)
.
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
v1 <- c(21,34,"99*",56,"90*", "45*")
you can use the method gsub .
a =c(21,34,"99*",56,"90*", "45*")
gsub("\\*","",a)
# result [1] "21" "34" "99" "56" "90" "45"
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.