Custom view `by =`
When I do table manipulations with by=
, the resulting table has the same record order as the original table:
dt1 <- fread(
"colA,colB
B,3
A,1
C,2
B,1
C,2
")
desired <- c('A', 'C', 'B')
#> dt1[, mean(colB), by=colA]
# colA V1
#1: B 2
#2: A 1
#3: C 2
But what if I need to have it not in this original order ( B A C
here) and not in the normal sort()
order (which would be A B C
or C B A
), but in my custom order (say A C B
)? Do I have to use rank
with the result table in any way ?
source to share
You can come back order
after doing the aggregation
dt1[, mean(colB), by=colA][order(desired),]
# colA V1
# 1: A 1
# 2: C 2
# 3: B 2
Thanks to Arun for fixing the problem. You have misplaced places on your desk. Remove them and then you can use order
(see above) or Arun's unification suggestion (below).
dt1[, colA := gsub(" ", "", colA)]
dt1[, mean(colB), keyby=colA][desired]
# colA V1
# 1: A 1
# 2: C 2
# 3: B 2
Look at the source data:
dt1 <- fread(
"colA,colB
B,3
A,1
C,2
B,1
C,2
")
dput(dt1)
# structure(list(colA = c(" B", " A", " C", " B", " C" ...
# extra space ----- ^^^
source to share