0
Ich bin auf eine Verhaltensstörung data.table
gestoßen, wo ich zeilenweise Operationen ausführen möchte, aber nicht tun kann, es sei denn, ich stelle zuerst eine Dummy-Variable zur Verfügung. Gibt es einen einstufigen Weg, um folgendes zu tun?Zeilenweise Operationen mit data.table mit der .I Notation
# I will calculate global vectorize max/min when going by `.I`
dt <- data.table(x=runif(10), y=runif(10))
dt[, c("max","min"):=list(max(x,y), min(x,y)), by =.I]
dt
# note max/min are the same across rows
x y max min
1: 0.9311597 0.89425124 0.9907917 0.06315146
2: 0.8007628 0.59832764 0.9907917 0.06315146
3: 0.6626013 0.90871193 0.9907917 0.06315146
4: 0.5857697 0.18239589 0.9907917 0.06315146
# creating a rowid will do the trick
# however, this requires three steps (create, calc, delete)
dt <- data.table(x=runif(10), y=runif(10))
dt[, rowid:=1:.N]
dt[, c("max","min"):=list(max(x,y), min(x,y)), by=rowid]
dt
# note each row is correctly calculated
x y rowid max min
1: 0.02321296 0.751962427 1 0.7519624 0.023212956
2: 0.93987266 0.504301816 2 0.9398727 0.504301816
3: 0.99621226 0.847503323 3 0.9962123 0.847503323
4: 0.66251070 0.003959591 4 0.6625107 0.003959591
`` `
Nur mit Verwendung' pmax' und 'pmin':' dt [c ("max", "min "): = Liste (pmax (x, y), pmin (x, y))]' – Jaap
Eine Randnotiz: Sie können Ausdrücke in 'by' haben (siehe Beispiele in'? data.table'). – Henrik
ihr seid super! Danke für die schnellen Antworten. – zach