user2051347
user2051347

Reputation: 1669

Convert comma separated data to numeric values

I have a data frame and want to convert part of it to numeric values like that:

> df$TotalReturn : 
str
 chr [1:3036] "182,83" "182,83" "186,4" "190,57" "191,17" 
              "193,25" "190,57" "184,02" "181,34" "172,11" 
              "169,73" "160,2" "175,09" "172,11" "170,92" 
              "176,58" "171,51" "170,92" "173,9" "168,54" 
              "167,34" "166,75" "166,45" "167,34" "164,37" "159,01" 
              "158,11" "154,84" "156,63" etc.

to convert it I use:

totalReturns <- (as.double(gsub(",",".",df$TotalReturn)))

However my data looks like that:

> totalReturns
str
 num [1:3036] 183 183 186 191 191 ...

Why is R rounding? How to get the full numeric/double value?

I appreciate your answers!

Upvotes: 1

Views: 815

Answers (1)

Roland
Roland

Reputation: 132626

It's only rounded for displaying with str:

str(as.double(gsub(",",".","182,83")))
#num 183

The vector is double precision:

as.double(gsub(",",".","182,83"))
#[1] 182.83

Note that you can specify the decimal separator when reading from a file (e.g., using read.table).

Upvotes: 4

Related Questions