【问题标题】:Printing significant figures regardless of decimal point打印有效数字,不考虑小数点
【发布时间】:2016-06-20 04:24:47
【问题描述】:

下表(平均值±标准差)包含将在出版物中呈现的真实数据。如您所见,数据范围非常广泛。使用 R,我将所有数字四舍五入为 3 个有效数字,但我想包括尾随零以及小数点左侧的零作为重要数字,以保持表格整洁。所以基本上我希望小数点两侧的所有数字(包括零)都被认为是重要的,因此无论数字如何,都只打印 3 位数字。这可能吗?我试过signifroundsprintfoptions()formatC,但没有成功。 这些结果是使用x$summary = paste(signif(x$Value, digits=3), "\u00b1", signif(x$se, digits=3))获得的

35.2 ± 3.13 > this is good
124 ± 14.8 > this is good
196 ± 6.53 > this is good
1.34 ± 0.0505 > I would like this to become 1.34 ± 0.05
0.0443 ± 0.00386 > I would like this to become 0.04 ± 0.00
123 ± 0.0067 > I would like this to become 123 ± 0.01

【问题讨论】:

  • 你从什么开始?现在它们是字符串,而不是数字。如果需要,您可以使用 strsplitas.numeric 转换回来。另外,您想要的输出是什么样的?
  • 显得模棱两可。你到底想看什么?
  • @alistaire 我编辑了问题以帮助澄清
  • 如果x是现有均值和错误的特征向量,使用purrr只是因为类似strsplit(x, ' ± ') %>% map(as.numeric) %>% map(round, digits = 2) %>% map_chr(paste, collapse = ' ± ')

标签: r rounding standard-error significant-digits


【解决方案1】:

我们可以试试gsubfn。在模式中,我们选择包括点的数字([0-9.]+),并通过先转换为numericas.numeric(x)),然后再转换为round来替换它。

library(gsubfn)
gsubfn("[0-9.]+", ~round(as.numeric(x), 2), v1)

除了rounding 之外,我们还删除了带有substr 的多余字符

gsubfn("[0-9.]+", ~substr(round(as.numeric(x), 3), 1, 4), v1)

或者使用sprintf 格式化roundded 数字,然后用sub 替换多余的尾随零。

sub("\\.0+\\s|0\\s", " ", gsubfn("[0-9.]+", ~sprintf("%.2f", 
        round(as.numeric(x), 2)), v1))
#[1] "35.2 ± 3.13" "124 ± 14.80" "196 ± 6.53"  "1.34 ± 0.05" "0.04 ± 0.00" "123 ± 0.01" 

数据

v1 <- c("35.2 ± 3.13", "124 ± 14.8", "196 ± 6.53", "1.34 ± 0.0505", 
                    "0.0443 ± 0.00386", "123 ± 0.0067")

【讨论】:

  • 这行得通!非常感谢。但尽我所能,我无法让它适合我用来从 SummarySE 生成表的脚本。您能否提供任何建议将您的代码(第二个效果最好)替换到这一行x$summary = paste(signif(x$Value, digits=3), "\u00b1", signif(x$se, digits=3))
  • @JCon 这里我们处理的是x$summary,即sub(...., gsubfn(....., x$summary))`
  • 谢谢,我想通了。你介意简要解释一下你的答案吗?我永远不会独自得出这个结论......
  • @J.Con 我添加了一些描述。希望对您有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多