Home > Blockchain >  Is there a function any function that convert character to double in R
Is there a function any function that convert character to double in R

Time:11-23

is there any function that converts things like : "1,8" to 1.8

I try as.double but it seems to not work.

I need to convert a column of a dataframe (whith only characters like this "1,3"). And I dont understand why, when I use as.double I've got only Nas

CodePudding user response:

Yes, there is! use parse_number from readr package

library(readr)
numbers <- c("1,8", "1,3")
parse_number(numbers, locale = locale(decimal_mark = ","))
# [1] 1.8 1.3

Or if you prefer using R base functions, you may want to use sub to substitute , by . and then apply as.numeric

as.numeric(sub(",", ".", numbers))
# [1] 1.8 1.3

CodePudding user response:

In base R, You can use scan:

numbers <- c('1,8', '1,3')

scan(text = numbers, dec = ',')
[1] 1.8 1.3

If the verbose is too long, invoke quiet = TRUE

scan(text = numbers, dec = ',', quiet = TRUE)
[1] 1.8 1.3
  • Related