[英]Formatting a data.frame: 3 digits after the decimal point
我有一個表格,它想格式化為小數點后的 3 位數字。
V1 <- c( 0.0727904610967749, 0.004670711, 0.022456166020719)
V2 <- c( 0.08111, NaN, 0.022222)
# Method 1
tab <- data.frame(V1=V1, V2=V2)
tab2 <- format(tab, digits=3)
# Method 2
is.num <- sapply(tab2, is.numeric)
tab2[is.num] <- lapply(tab2[is.num], round, 3)
兩者都給我:
這是我期望看到的。 我怎樣才能做到這一點?
另一種選擇是使用dplyr
:
tab %>%
mutate_if(is.numeric, ~ round(.,3))
或者
tab %>%
mutate_if(is.numeric, ~ scales::number(., accuracy = 0.001))
# V1 V2
# 1 0.073 0.081
# 2 0.005 <NA>
# 3 0.022 0.022
您可以將apply
與round
一起使用:
apply(tab, 2, function(x) round(x, 3))
V1 V2
[1,] 0.073 0.081
[2,] 0.005 NaN
[3,] 0.022 0.022
apply(tab, 2, f)
將 function f
應用於tab
的每一列(即2
代表的內容)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.