3

dcast.data.table automatically renames columns when multiple aggregation functions are used. How can I use this rename when I use only one function?

DT = melt(as.data.table(ChickWeight), id=2:4)
% automatic rename
data.table::dcast(DT, Time ~ variable, fun=list(mean, sd))
% copies only the factor level
data.table::dcast(DT, Time ~ variable, fun=mean)
Dirk
  • 1,134
  • 2
  • 12
  • 21
  • 1
    Probably not the answer you're looking for, but maybe worth nothing you could rename as desired to the right of `~` i.e. `data.table::dcast(DT, Time ~ paste0('mean_', variable), fun = mean)` – IceCreamToucan Dec 19 '19 at 14:04
  • 1
    A workaround would be to supply a second function and then remove the extra column: `data.table::dcast(DT, Time ~ variable, fun=list(mean, sum))[, -3] ` – G. Grothendieck Dec 19 '19 at 15:20
  • @IceCreamToucan Thanks! However, this doesn't use the build in naming from `dcast` which adds, for instance, the level to the corresponding column. – Dirk Dec 20 '19 at 06:46
  • @G.Grothendieck Thank you, too! I thought also about this workaround. However, when using large datasets with an undefined number of levels in `variable` this is time consuming and I have to take care to delete the correct columns. Currently, I see no alternative. – Dirk Dec 20 '19 at 06:48

0 Answers0