I am trying to apply currency formatting to TOTAL in a grouped data frame using formattable. However I get the error: "TOTAL" must return compatible vectors across groups.
Here's some reproducible code that produces the error:
library(dplyr)
library(formattable)
n <- 100
data <- data.frame(
FY = round(runif(n, 2020, 2025), digits = 0),
LOBJ = round(runif (n, 1, 10), digits = 0),
VALUE = rnorm(n, 50, 20)
)
data_summary <- data %>%
group_by(FY, LOBJ) %>%
summarize(TOTAL = sum(VALUE)) %>%
mutate(TOTAL = currency(TOTAL))
What am I doing wrong? Thanks in advance!
You could do it by using
summarise()making a list and then unseating the result. That will keep the grouping structure and do the right thing with thecurrency()formatting:It also works as you wrote it if you ungroup the data before calling
mutate().Created on 2024-01-26 with reprex v2.0.2