Vassilis Chasiotis
Vassilis Chasiotis

Reputation: 439

How to convert character argument (decimal number) to numeric in R?

I want to convert for example the number 167009345.8 to 167009345.8.

I have used lots of ways but I have problems.

For example,

x <- "167009345.8"
class(x) <- "numeric"`

the output is 167009346.

But I want the decimal number 167009345.8.

I have used also as.numeric, but I have the same problem.

Could you please help me?

Upvotes: 4

Views: 11659

Answers (3)

Monika Wahi
Monika Wahi

Reputation: 1

Thanks for the solution by @Meije the sheep. This was a great answer for me! I modified it a little for df processing.

My dataframe (df) has a character variable called Score. Example values: "33.3333333333333" "51.8518518518518" "15.4471544715447"

To convert it to numeric (Score_n) I did the following, then dropped df$string, df$charlist, and df$numberlist.

df$string = df$Score
df$charlist = strsplit(df$string, "," )
options(digits=10)
df$numberlist = lapply(df$charlist, function(x) (as.numeric(x)))
df$Score_n = as.numeric(unlist(df$numberlist))

Upvotes: 0

Meije the sheep
Meije the sheep

Reputation: 21

I had to split a long character string into separate decimal numbers. It was very frustrating. Maybe this can spare some others some time:

string = as.character("1.23456, -2.34567, -8.90, +0, +99999.9999, -0.0")
charlist = strsplit(string, "," )
numberlist = lapply(charlist, function(x) (as.numeric(x)))
vector = as.numeric(unlist(numberlist))
vector
[1]      1.23456     -2.34567     -8.90000      0.00000  99999.99990      0.00000

Upvotes: 0

r.bot
r.bot

Reputation: 5424

options(digits=10)
x<-"167009345.8"
as.numeric(x)
[1] 167009345.8

Upvotes: 5

Related Questions