我试图对表摘要上的值进行舍入,但舍入应用于整个表而不是一个部分。如何将round()应用于表中总结的最后一行?round()似乎被忽略。示例如下:
library(dplyr)
library(tidyr)
library(gt)
Data:
a <- structure(list(SampleDate = structure(c(15710, 15713, 15713,
15710, 15710, 15713, 15713, 15710, 15708, 15713, 15712, 15708,
15708, 15713, 15712, 15708), class = "Date"), year = c("2012",
"2013", "2013", "2012", "2013", "2013", "2013", "2013", "2013",
"2012", "2013", "2013", "2013", "2013", "2013", "2013"), F = c(0,
1, 0, 0, 0, 1, 0, 0, 0, 22, 0, 0, 0, 65, 0, 0), W = c(0, 0, 1,
0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0), S = c(0, 0, 0, 0, 1,
0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0), LF = c(1, 0, 0, 1, 0, 0, 0,
1, 0, 0, 0, 0, 1, 0, 0, 1), week = c("01", "02", "02", "01",
"01", "02", "02", "01", "01", "02", "02", "01", "01", "02", "02",
"01"), month = c("January", "January", "January", "January",
"January", "January", "January", "January", "January", "January",
"January", "January", "January", "January", "January", "January"
)), row.names = c(NA, -16L), class = "data.frame")
a
a %>%
group_by(year,SampleDate) |>
summarise(F = sum(F), W = sum(W), S = sum(S), LF = sum(LF),count = n()) |>
ungroup() %>%
mutate_at(vars(year:SampleDate), funs(as.character(.))) %>%
**#Only want to round to 2 decimals the Summed field below**
bind_rows(summarise(year = 'Summed', SampleDate = '- - - - -', a, F = round(sum(F),2),
W = round(sum(W),2), S = round(sum(S),2), LF = round(sum(LF),2),
count = n())) |> gt()
2条答案
按热度按时间smdncfj31#
问题是,如果数字为零,
round()
不会显示数字。我们通常使用sprintf
。我会用gt::fmt_number()
来格式化。这里我们可以指定columns
和rows
以及decimals
:数据来自OP
yzuktlbb2#
gt
具有创建汇总行的函数:grand_summary_rows()
和summary_rows()
。您可以使用fmt_numbers()
控制显示的小数。您可以添加另一个grand_summary_rows()
调用,以便为不同的列集添加第二个汇总行。如果要计算同一组列的多个汇总行,可以在fns
参数中list()
多个汇总行规范。在下面的示例中,我将mutate_at()
更改为mutate(across(...))
表达式,它取代了mutate_at()
等。