首页 > 解决方案 > 格式化data.frame:小数点后3位

问题描述

我有一个表格,它想格式化为小数点后的 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)

两者都给我:

在此处输入图像描述

这是我期望看到的。我怎样才能做到这一点?

在此处输入图像描述

标签: rdataframeformatapply

解决方案


另一种选择是使用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

推荐阅读