r - 格式化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)
两者都给我:
这是我期望看到的。我怎样才能做到这一点?
解决方案
另一种选择是使用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
推荐阅读
- c++ - Arduino无线nrf24l01 i2c运行缓慢
- spring - 在 DataJPATest 下运行单元测试时出现问题
- web - 制作社交媒体网站时使用了哪些语言?
- java - 在 GUICE 中继承 AOP 的注解
- rust - actix 和 tokio_postgres 的生命周期错误
- php - 将 API 响应导出到 CSV
- python - 从类成员函数返回一个有效的 self 对象在调用者方法中被评估为 None
- java - Java ImageIO:检查带有 alpha 的 PNG 是否不透明?
- react-native - 尝试在本机反应中访问状态时“未定义不是对象”
- sql - SQL连接表并根据数据将第二个表显示为两列