Remove Characters from a Column

I have a vector of numbers with few values containing characters:

[1] "8" "3" "3" "7" "1" "7" "4" "2" "5" "4" "3" "3" "3"
[14] "8" "3" "5" "1" "1" "3" "5" "1" "1" "5" "2" "4" "9"
[27] "3" "8" "5" "3" "0" "3" "4" "1" "5" "3" "2" "3" "6"
[40] "9" "6" "8 წლის" "3" "6" "5" "2 წლის" "2" "2" "6 clis" "4" "7" "3"
[53] "8" "8" "8" "3" "4"

How do I remove the characters to leave only the numbers and at the same time (if applicable) convert the column to numeric?

If your numbers always precede the characters, this should work.

library(stringr)
VEC <- c(1,2,3,"4ER","5ERT",1)
VEC
#> [1] "1"    "2"    "3"    "4ER"  "5ERT" "1"
NewVec <- str_extract(VEC,"^\\d+")
NewVec <- as.numeric(NewVec)
NewVec
#> [1] 1 2 3 4 5 1

Created on 2021-01-15 by the reprex package (v0.3.0)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.