Rameez Shaik
Rameez Shaik

Reputation: 31

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).

Upvotes: 1

Views: 10480

Answers (2)

Mukesh Kumar Singh
Mukesh Kumar Singh

Reputation: 653

you can use the method gsub .

a =c(21,34,"99*",56,"90*", "45*") 
gsub("\\*","",a)


# result [1] "21" "34" "99" "56" "90" "45"

Upvotes: 1

akrun
akrun

Reputation: 887158

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*") 

Upvotes: 6

Related Questions