I think the issue is when you define in x in your function you are not supplying the labels so it just puts the factor levels in alphabetical order, so I think you just need to add the labels to your function.
DT$fc_x <- cut(DT$x, breaks = c(0, 50, 100, 10e5), rigth = T,
labels = c("0-50", "51-100", "+100"))
factor(levels(DT$fc_x))
[1] 0-50 51-100 +100
Levels: 0-50 +100 51-100
factor(levels(DT$fc_x), labels = c("0-50", "51-100", "100+"))
[1] 0-50 +100 51-100
Levels: 0-50 51-100 +100
grp <- function(x) {
percentage = as.numeric(table(x)/length(x))
list(
x = factor(levels(x), labels = levels(x)),
percentage = percentage,
label = paste0( round( as.numeric(table(x)/length(x), 0 ) * 100 ), "%")
)
}
DT <- data.table(x = rnorm(100, 100, 50), fac = factor(letters[1:10]))
DT$fc_x <- cut(DT$x, breaks = c(0, 50, 100, 10e5), rigth = T,
labels = c("0-50", "51-100", "+100"))
AGG <- DT[, grp(fc_x), by=fac]
levels(AGG$x)
[1] "0-50" "51-100" "100+"