僅當數字小于 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)
uj5u.com熱心網友回復:
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) 基 R或僅基 R(格式來自上面)
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) 折疊 格式來自上面。
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)
uj5u.com熱心網友回復:
你可以apply在兩個邊緣1:2。
as.data.frame(apply(tab, 1:2, \(x) format(x, digits=1, nsmall=3)))
# col1 col2
# 1 2e-05 3.500
# 2 1e-04 45.655
# 3 0.569 12585.566
或者,如果您只想格式化一個特定的列:
transform(tab, col1=sapply(col1, format, digits=1, nsmall=3))
# col1 col2
# 1 2e-05 3.50000
# 2 1e-04 45.65465
# 3 0.569 12585.56630
重要的是,每個元素都是單獨格式化的。
這是另一種使用replace.
tab |>
round(5) |>
(\(.) replace(., . < 1e-4, format(.[. < 1e-4], digit=1, nsmall=3)))()
# col1 col2
# 1 2e-05 3.50000
# 2 1e-04 45.65465
# 3 0.56898 12585.56630
uj5u.com熱心網友回復:
lapply(tab, \(x) ifelse(abs(x) < 0.0001, format(x, scientific=TRUE), format(x, scientific=FALSE)))
# $col1
# [1] "2.000000e-05" "0.0001000" "0.5689786"
# $col2
# [1] " 3.50000" " 45.65465" "12585.56630"
如果您愿意,您可以重新分配回框架tab[] <- lapply(tab, ...)。請注意,所有列現在character都不是numeric。
這也許可以做稍微更有效地在作業matrix,現在沒有必要lapply:
tab <- cbind(col1, col2)
ifelse(tab < 0.0001,
format(tab, digit=1, nsmall=3),
format(tab, digit=1, nsmall=3, scientific=FALSE))
# col1 col2
# [1,] "2e-05" " 3.50000"
# [2,] " 0.00010" " 45.65465"
# [3,] " 0.56898" "12585.56630"
然后可以將其轉換為框架。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/397032.html
標籤:r
