Building on @eddi's answer, I've created a hackish solution where I store an unevaluated call to order
as an attribute of the data.table
, which print.data.table
obeys:
set_order <- function(dt, cols, decreasing=FALSE) {
# Store a call to order as an additional attribute
attr(dt, "order") <- paste0("order(", paste(cols, collapse=", "),
", decreasing=", decreasing, ")")
invisible(dt)
}
print.data.table = function(x, ...) {
if (!is.null(attr(x, "order"))) {
# Use the stored ordering to print the data.table
data.table:::print.data.table(x[eval(parse(text=attr(x, "order")))], ...)
} else {
data.table:::print.data.table(x, ...)
}
}
Giving me the behaviour I want:
dt <- set_order(dt, c("group", "value.1"), decreasing=T)
dt
# id group value.1 value.2
# 1: f red -0.4816474 0.23658045
# 2: b red -0.6443284 0.49924102
# 3: d red -1.5977095 0.08033604
# 4: e blue 1.8050975 0.43553048
# 5: a blue 1.4557851 0.73249612
# 6: c blue -1.5531374 0.72977197
tables()
# NAME NROW MB COLS KEY
# [1,] dt 6 1 id,group,value.1,value.2 id
# Total: 1MB