Das folgende Problem hindert mich bisher an einer wirklich flexiblen Nutzung von data.table aggregations.Flexibles Mischen mehrerer Aggregationen in data.table für verschiedene Spaltenkombinationen
Beispiel:
library(data.table)
set.seed(1)
DT <- data.table(C1=c("a","b","b"),
C2=round(rnorm(4),4),
C3=1:12,
C4=9:12)
sum_cols <- c("C2","C3")
#I want to apply a custom aggregation over multiple columns
DT[,lapply(.SD,sum),by=C1,.SDcols=sum_cols]
### Part 1 of question ###
#but what if I want to add another aggregation, e.g. count
DT[,.N,by=C1]
#this is not working as intended (creates 4 rows instead of 2 and doesnt contain sum_cols)
DT[,.(.N,lapply(.SD,sum)),by=C1,.SDcols=sum_cols]
### Part 2 of question ###
# or another function for another set of colums and adding a prefix to keep them appart?
mean_cols <- c("C3","C4")
#intended table structure (with 2 rows again)
C1 sum_C2 sum_C3 mean_C3 mean_C4
Ich weiß, dass ich immer verschiedene einzelne Aggregation Ergebnisse von einigen Schlüssel zusammenführen können, aber Ich bin mir sicher muss es eine richtige, flexible und einfache Art und Weise zu tun, was ich tun möchte (vor allem Teil 2).
Toll, danke - das wird mein Leben mit dt viel einfacher und bequemer machen. Leistung kommt an zweiter Stelle (in diesem Fall) - Ich werde Ihre Anmerkungen überprüfen, wenn ich auf Probleme stoße. Ich bin allerdings überrascht, dass das .SDcols hier nicht so hilfreich ist ... es scheint im Allgemeinen ziemlich begrenzt zu sein. – katsumi
@katsumi Yeah, .SDcols ist nur für eine Reihe von Cols auf einmal, also wenn Sie mehrere (möglicherweise überlappende) Sets wollen, wird es nicht so nützlich sein, denke ich. – Frank