【问题标题】:Convert string to numeric defining the number of decimal digits将字符串转换为定义小数位数的数字
【发布时间】:2015-10-06 15:45:23
【问题描述】:

从给定的地理参考点数据框架中,我在字符列中找到了坐标,格式如下

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

为了从每一行中提取数值,我使用了以下命令(我将以第一行为例)。

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 全局设置的情况下将字符串转换为数字设置小数位数?

【问题讨论】:

    标签: r string numeric


    【解决方案1】:

    您实际上并没有丢失数字;这就是它被打印到控制台的方式:

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

    正如 David Arenburg 在 cmets 中指出的那样,您也可以使用 print(..., digits = &lt;n&gt;)

    【讨论】:

    • 或者print(as.numeric(res[[1]]), digits = 12),因为我们实际上在这里处理print函数。
    • sprintf("%.10f", as.numeric(res[[1]][1]),其中 10 可以替换为您希望的任意多个 sig-digits
    • sprintf() 只是带​​你回到字符。
    • 我已经使用 print(..., digits = ) 解决方案解决了我的僵局。感谢您分享您的解决方案。最后一个边缘问题:是否可以在使用 options(digits = 12) 之前将当前位数保存在变量中
    • 如果我理解您的要求,通常在更改任何选项之前执行old.opts &lt;- options() 之类的操作,以便您使用options(old.opts) 恢复它们。或者,如果您只想存储单个选项,您可以使用 getOption("digits")options()["digits"] 访问它们。
    【解决方案2】:

    以获取数字作为结果的目标并采用@nrussell 在上一个答案(以及以下 cmets)中提供的建议,我找到了以下解决方案:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-09
      • 2019-11-15
      • 2015-05-25
      • 2019-05-11
      • 2015-08-25
      • 1970-01-01
      • 2014-09-08
      • 2017-06-18
      相关资源
      最近更新 更多