2015-10-06 39 views
3

数量从georeferred点的给定data.frame我发现在格式化为一个字符列的坐标遵循字符串转换为数字限定的十进制数字

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

要从I”各行中提取的数值我使用了以下命令(以第一行为例)。

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 

在此转换中,我丢失了6位十进制数字。 有没有一种方法可以将字符串转换为数字来设置小数位数,而无需修改任何R全局设置?

回答

6

你实际上并没有丢失数字;这是多么被打印到控制台:

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

正如大卫Arenburg的评论,你也可以使用print(..., digits = <n>)指出。

+2

或者'print(as.numeric(res [[1]]),digits = 12)',因为我们在这里实际处理'print'函数。 –

+1

或'sprintf(“%。10f”,as.numeric(res [[1]] [1])'其中10可以被你希望的多个sig-digits代替 –

+2

'sprintf()'只是把你带回来 –

0

以客观,获得作为结果的数量,并采用由@nrussell在以前的答案提供的建议(及后续评论)我已经找到了以下解决方案:

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 

一个更简单的方法避免字符串分割如下

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 
相关问题