Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to numeric defining the number of decimal digits

Tags:

string

r

numeric

From a given data.frame of georeferred points I found the coordinate in a character column formatted as follow

"44.524768336 11.4832955249"
"44.6858512233 11.1698766486"
"44.498179364 11.6599683838"

To extract the numeric values from each rows I've used the following commands (I'll take the first row as example).

res <- strsplit(x = "44.524768336 11.4832955249", split = " ", fixed = T)
res
[[1]]
[1] "44.524768336"  "11.4832955249"

as.numeric(res[[1]][1])
[1] 44.52477
as.numeric(res[[1]][2])
[1] 11.4833

In this conversion I've lost 6 decimal digits. Is there a method to convert strings to numbers setting the number of decimal places without modify any R global setting?

like image 370
Tiziano Avatar asked Feb 09 '23 21:02

Tiziano


1 Answers

You didn't actually lose the digits; that's just how it is being printed to the console:

options(digits = 4)
R> as.numeric(res[[1]][1])
#[1] 44.52
## 
options(digits = 12)
R> as.numeric(res[[1]][1])
#[1] 44.524768336

As pointed out in the comments by David Arenburg you can also use print(..., digits = <n>).

like image 166
nrussell Avatar answered Feb 11 '23 14:02

nrussell