Ich habe zwei Datentabellen wie folgt hinzufügen:R, data.table: programmatisch Spalte berechneten Daten und Namen aus einer anderen Datentabelle
set.seed(1)
landing_fees <- data.table(`date`= c(20160101,20160101,20160101,
20160102,20160102,20160102,20160103,20160103,20160103),
airport=c("LAX","PHX","HNL"), period_a_fee=sample(100:200,9),
period_b_fee=sample(100:200,9), period_c_fee=sample(100:200,9))
routes <- data.table(origin=c(rep("LAX",4),rep("PHX",4)),
destination=c("PHX","HNL","PHX","HNL","LAX","HNL","LAX","HNL"),
period=rep(c("period_a","period_a","period_b","period_c"),2))
Welche Ausgabe wie folgt:
> landing_fees
date airport period_a_fee period_b_fee period_c_fee
1: 20160101 LAX 126 106 138
2: 20160101 PHX 137 120 177
3: 20160101 HNL 156 117 192
4: 20160102 LAX 189 167 120
5: 20160102 PHX 119 137 163
6: 20160102 HNL 186 173 112
7: 20160103 LAX 197 147 125
8: 20160103 PHX 162 197 136
9: 20160103 HNL 158 192 101
> routes
origin destination period
1: LAX PHX period_a
2: LAX HNL period_a
3: LAX PHX period_b
4: LAX HNL period_c
5: PHX LAX period_a
6: PHX HNL period_a
7: PHX LAX period_b
8: PHX HNL period_c
der realen Datensätze sind riesig mit Millionen von Ursprung/Ziel Kombinationen und Jahren im Wert von Daten. Ich möchte eine neue Spalte zu der Routentabelle für jedes eindeutige Datum in landing_fees $ date hinzufügen und die Spalte mit dem Datum und _cost (dh 20160101_cost) programmatisch benennen. Dann summieren Sie in jeder neuen Spalte die Gebühr für den Ursprung und die Gebühr für das Ziel (unter Verwendung des passenden Zeitraums) wie in der Tabelle "landing_fees" aufgelistet. Zum Beispiel würde in der routes-Tabelle eine neue Spalte routes $ 20160101_cost erzeugt und der Wert von row 1 wäre: LAX period_a Fee von 126 (aus der Tabelle landing_fees) plus PHX period_a Fee von 137 (aus der Tabelle landing_fees) gleich 263. Die gleiche Berechnung würde für jede Kombination aus Ursprung/Ziel/Zeitraum für jedes Datum durchgeführt.
fertige Ausgabe würde wie folgt aussehen:
origin destination period 20160101_cost 20160102_cost 20160103_cost
1: LAX PHX period_a 263 308 359
2: LAX HNL period_a 282 375 355
3: LAX PHX period_b 226 304 344
4: LAX HNL period_c 330 232 226
5: PHX LAX period_a 263 308 359
6: PHX HNL period_a 293 305 320
7: PHX LAX period_b 226 304 344
8: PHX HNL period_c 369 275 237
Da die Datensätze ziemlich groß sein können, ich hoffe, effizientes data.table Skript zu verwenden. Ich benutze data.table Version 1.9.6 auf Windows 7 Maschine.