Reputation: 321
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?
Upvotes: 6
Views: 22079
Reputation: 321
Taking the objective to obtain as results a number and adopting the suggestions provided by @nrussell in the previous answer (and followings comments) I've found the following solution:
string.number <- "44.004768336"
# Splitting the string in integer and decimal part
number.part <- strsplit(string.number, ".", fixed = T)
as.numeric(number.part[[1]][1]) # Integer part
[1] 44
as.numeric(number.part[[1]][2]) # Decimal part. Note the effect of the leading zeros
[1] 4768336
# saving the current and set the new setting the "digits" option
getOption(x = "digits")
[1] 11
current.n.dgt <- getOption("digits")
options(digits = 11)
# Combining integer and decimal in a number saving the required numbers of decimal digits
integer.part <- as.numeric(number.part[[1]][1])
exp.numb <- (trunc(log10(as.numeric(number.part[[1]][2])))+1+(nchar(number.part[[1]][2])-nchar(as.character(as.numeric(number.part[[1]][2])))))
decimal.part <- as.numeric(number.part[[1]][2])/(10^exp.numb)
res.number <- integer.part + decimal.part
res.number
[1] 44.004768336
A more simple way to avoid the string splitting is the following
getOption("digits")
[1] 7
current.n.dgt <- getOption("digits")
string.number <- "44.004768336"
options(digits = 11)
as.numeric(string.number)
[1] 44.004768336
options(digits = current.n.dgt)
getOption("digits")
[1] 7
Upvotes: 0
Reputation: 18602
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>)
.
Upvotes: 9