gpt4 book ai didi

r - 将数字列表转换为字符时,如何控制数字的格式?

转载 作者:行者123 更新时间:2023-12-05 04:13:43 25 4
gpt4 key购买 nike

例如,我有一个包含数字的嵌套列表

x <- list(1 + .Machine$double.eps, list(rnorm(2), list(rnorm(1))))

如果我对此调用 as.character,所有数字都以固定格式给出,保留 15 位有效数字。

as.character(x)
## [1] "1"
## [2] "list(c(0.654345721043012, 0.611306113713901), list(-0.278722330674071))"

我希望能够控制数字的格式。至少,我希望能够控制包含多少有效数字。作为奖励,能够指定科学格式而不是固定格式会很好。

?as.character 帮助页面指出:

as.character represents real and complex numbers to 15 significant digits (technically the compiler's setting of the ISO C constant DBL_DIG, which will be 15 on machines supporting IEC60559 arithmetic according to the C99 standard). This ensures that all the digits in the result will be reliable (and not the result of representation error), but does mean that conversion to character and back to numeric may change the number. If you want to convert numbers to character with the maximum possible precision, use format.

因此,似乎无法直接使用 as.character 更改格式。

调用format破坏列表结构:

format(x, digits = 5)
## [1] "1" "0.65435, 0.61131, -0.27872"

formatC 抛出关于不支持列表输入的错误。

deparse 也不允许用户更改数字的格式:as.character(x)vapply(x, deparse,字符(1)).

这几乎是正确的,但是我不想要数字周围有额外的双引号字符:

as.character(rapply(x, format, digits = 5, how = "list"))
## [1] "1"
## [2] "list(c(\"0.65435\", \"0.61131\"), list(\"-0.27872\"))"

如何控制数字的格式?


部分解决方案:为了减少有效数字的数量,我可以通过使用格式转换为字符,然后再转换回数字来调整前面的示例。

as.character(rapply(x, function(x) as.numeric(format(x, digits = 5)), how = "list"))
## [1] "1" "list(c(-1.0884, 1.6892), list(0.58783))"

如果我想将 sig figs 的数量增加到 15 以上或使用科学格式(因为我们遇到了 as.character 的限制),这将不起作用。

as.character(rapply(x, function(x) as.numeric(format(x, digits = 22)), how = "list"))
## [1] "1"
## [2] "list(c(-1.08842504028146, 1.68923191896784), list(0.5878275490431))"

最佳答案

玩转 rapply()how 参数:

> rapply(x, sprintf, fmt = "%0.5f", how = "replace")
[[1]]
[1] "1.00000"

[[2]]
[[2]][[1]]
[1] "0.18041" "-0.63925"

[[2]][[2]]
[[2]][[2]][[1]]
[1] "0.14309"

要获取更多数字,请更改 fmt:

> rapply(x, sprintf, fmt = "%0.22f", how = "replace")
[[1]]
[1] "1.0000000000000002220446"

[[2]]
[[2]][[1]]
[1] "1.2888001496908956244880" "1.0289289081633956612905"

[[2]][[2]]
[[2]][[2]][[1]]
[1] "0.4656598705611921240610"

您可以gsub() 引号:

> gsub("\"", "", deparse(rapply(x, function(z) sprintf(fmt = "%0.22f", z), how = "replace")))
[1] "list(1.0000000000000002220446, list(c(1.2888001496908956244880, "
[2] "1.0289289081633956612905), list(0.4656598705611921240610)))"

关于r - 将数字列表转换为字符时,如何控制数字的格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37025196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com