本文介绍了打印时在dplyr tbl_df中四舍五入数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图将真实值保留在dplyr表(tbl_df)中,但显示四舍五入的版本。我觉得必须有一个打印方法参数才能做到这一点。
I'm trying to keep the true values in a dplyr table (tbl_df) but display rounded versions. I feel like there must be a printing method argument to do this.
以下是我想要的示例:
my_tbl <- iris %>% group_by(Species) %>% summarise_each(funs((sum(.*12345e20))))
相反:
print(my_tbl)
Source: local data frame [3 x 5]
Species Sepal.Length Sepal.Width Petal.Length Petal.Width
(fctr) (dbl) (dbl) (dbl) (dbl)
1 setosa 3.089954e+26 2.115933e+26 9.024195e+25 1.518435e+25
2 versicolor 3.663996e+26 1.709783e+26 2.629485e+26 8.184735e+25
3 virginica 4.066443e+26 1.835702e+26 3.426972e+26 1.250549e+26
我想要类似
print(my_tbl, signif=3)
Source: local data frame [3 x 5]
Species Sepal.Length Sepal.Width Petal.Length Petal.Width
(fctr) (dbl) (dbl) (dbl) (dbl)
1 setosa 3.09e+26 2.12e+26 9.02e+25 1.52e+25
2 versicolor 3.66e+26 1.71e+26 2.63e+26 8.18e+25
3 virginica 4.07e+26 1.84e+26 3.43e+26 1.25e+26
推荐答案
您可以重写 dplyr ::: print.tbl_df
以包含 signif
参数。
You could rewrite dplyr:::print.tbl_df
to include a signif
argument.
print.tbl_df <- function (x, ..., signif = 3, n = NULL, width = NULL)
{
nums <- vapply(x, is.numeric, NA)
x[nums] <- lapply(x[nums], signif, digits = signif)
cat("Source: local data frame ", dim_desc(x), "\n", sep = "")
cat("\n")
print(trunc_mat(x, n = n, width = width))
invisible(x)
}
my_tbl <- iris %>% group_by(Species) %>% summarise_each(funs((sum(.*12345e20))))
现在任何 tbl_df
打印的默认有效数字为3。
Now any tbl_df
prints with the default significant digits of 3.
my_tbl
# Source: local data frame [3 x 5]
#
# Species Sepal.Length Sepal.Width Petal.Length Petal.Width
# (fctr) (dbl) (dbl) (dbl) (dbl)
# 1 setosa 3.09e+26 2.12e+26 9.02e+25 1.52e+25
# 2 versicolor 3.66e+26 1.71e+26 2.63e+26 8.18e+25
# 3 virginica 4.07e+26 1.84e+26 3.43e+26 1.25e+26
要使用其他有效数字进行打印,我们可以使用 print()
。
To print with other significant digits, we can use print()
.
print(my_tbl, signif = 5)
# Source: local data frame [3 x 5]
#
# Species Sepal.Length Sepal.Width Petal.Length Petal.Width
# (fctr) (dbl) (dbl) (dbl) (dbl)
# 1 setosa 3.0900e+26 2.1159e+26 9.0242e+25 1.5184e+25
# 2 versicolor 3.6640e+26 1.7098e+26 2.6295e+26 8.1847e+25
# 3 virginica 4.0664e+26 1.8357e+26 3.4270e+26 1.2505e+26
这篇关于打印时在dplyr tbl_df中四舍五入数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!