R clears a character and converts it to numeric

R clearing a character string and converting it to a numeric number

I have a character string

abc <- "Â 267750Â" class(abc) "character" 

What do I need to do for abc to get rid of “ ” and convert it from character to numeric. Perhaps as.numeric will work, but I need to get rid of “ ” first.

I want to convert above:

 abc 267750 class(abc) "numeric" 

Thank you for your help.

+4
source share
2 answers

You can parse what you don't want with regular expressions:

 test <- "532.dcx3vds98" destring <- function(x,keep="0-9.") { return( as.numeric(gsub(paste("[^",keep,"]+",sep=""),"",x)) ) } destring(test) 

Returns 532.398 .

Edit

Now this is in taRifx :

 library(taRifx) test <- "532.dcx3vds98" destring(test) 
+7
source

a little shorter using stringr :

  # load library library(stringr) # load data abc <- "Â 267750Â" # extract digits abc <- as.numeric(str_extract(abc, "[0-9]+")) # check the result abc [1] 267750 class(abc) [1] "numeric" 
+5
source

Source: https://habr.com/ru/post/1401834/


All Articles