I am trying to use the dplyr %>% pipeline to round and format the numeric values to have 2 digits after the decimal point (e.g. 2.43, 1.05). However, the format() function have different behaviors in the below two data examples (df_summarize and df_groupby). The output of the df_summarize is correct, but the output of df_groupby is not correct, I wonder what's the reason for the wired behavior. Is that because of the grouping effect or something else?
Any suggestions are appreciated.
library(tidyverse)
df <- data.frame(cate = sample(c("A", "B"), size = 5, replace = T),
v1 = runif(5, 1.001, 5.005),
v2 = runif(5, 1.001, 5.005))
df_summarize <- df %>% summarise(mean_v1 = mean(v1),
mean_v2 = mean(v2)) %>%
round(2) %>% format(nsmall = 2)
# mean_v1 mean_v2
# 1 3.94 2.08
df_groupby <- df %>% group_by(cate) %>%
summarise(p1 = mean(v1), p2 = mean(v2)) %>%
select(-cate) %>% ungroup() %>%
round(2) %>% format(nsmall = 2)
# [1] "\033[38;5;246m# A tibble: 2 × 2\033[39m"
# [2] " p1 p2"
# [3] " \033[3m\033[38;5;246m<dbl>\033[39m\033[23m \033[3m\033[38;5;246m<dbl>\033[39m\033[23m"
# [4] "\033[38;5;250m1\033[39m 4.01 2.17"
# [5] "\033[38;5;250m2\033[39m 3.67 1.69"