gpt4 book ai didi

r - 仅适用于数据集列的特定数字的科学记数法

转载 作者:行者123 更新时间:2023-12-02 16:01:38 24 4
gpt4 key购买 nike

我需要格式化数据框的数字列,仅当数字小于 0.0001 时才显示科学记数法。我在使用 format 函数的地方编写了以下代码。此代码的问题在于它会转换所有数字。

有什么建议吗?

col1 <- c(0.00002, 0.0001, 0.5689785541122558)
col2 <- c(3.5, 45.6546548788, 12585.5663)
tab <- cbind(col1, col2)
tab <- as.data.frame(tab)
format(tab[1], digit = 1, nsmall = 3)

最佳答案

1) dplyr 定义矢量化格式并在 mutate/across 中使用它:

formatv <- function(x, ...) {
mapply(format, x, scientific = abs(x) < 0.0001, ...)
}

library(dplyr)
tab %>% mutate(across(, formatv, digit = 1, nsmall = 3))

2) Base R or only base R (formatv is from above)

replace(tab, TRUE, lapply(tab, formatv, digit = 1, nsmall = 3))

replace(tab, TRUE, formatv(as.matrix(tab), digits = 1, nsmall = 3))

或者如果你有少量的列,则分别做每一个

transform(tab,
col1 = formatv(col1, digits = 1, nsmall = 3),
col2 = formatv(col2, digits = 1, nsmall = 3))

3) collapse 格式来自上方。

library(collapse)
ftransformv(tab, names(tab), formatv, digit = 1, nsmall = 3)

4)purrr 可以使用purrr中的map_dfc。 formatv 来自上面。

library(purrr)
tab %>% map_dfc(formatv, digit = 1, nsmall = 3)

关于r - 仅适用于数据集列的特定数字的科学记数法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70520585/

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