Home > Software design >  Convert a column of character mode into numeric in R?
Convert a column of character mode into numeric in R?

Time:11-23

I downloaded historical prices of an index but all prices are characters, that is are of the form : "24,31" (and i checked the mode).

I tried several things, such as :

as.numeric(as.character(VDAXcsv$Dernier))

which returns only NAs, or :

sapply(VDAXcsv$Dernier, as.numeric) | sapply(VDAXcsv, as.numeric)

Or simply

as.numeric(VDAXcsv)

And still only NAs, besides I tried to put "stringsAsFactors=FALSE" into my "read.zoo" function but it doesn't change anything. as.format doesn't work either.

CodePudding user response:

x <- "24,31"
y <- as.numeric(gsub(",", ".", x))
y
# [1] 24.31
class(y)
# [1] "numeric"

A side note

I think depending on the data file you have, you might even want to prevent this to happen in the first place defining dec. Be careful if your sep is a comma as well though. It still can be an option, so you do not get your values as a character and therefor no need to do any replacements.

fread(file, header = T, sep = ";", dec = ",") # fread is data.table, but I think read.csv and any others support it as well

CodePudding user response:

You can use this function:

library(readr)

parse_number("24,31", locale = locale(decimal_mark = ","))

Is vectorized, so just put VDAXcsv$Dernier as first argument.

  • Related