R data.table: (dynamic) forward looking Cross-Joins -
i wondering if there option cj() method in data.table take vectors formed evaluated condition instead of running full cross join.
data
library(data.table) df<-data.table( id=c(18l, 18l, 18l, 46l, 74l, 74l, 165l, 165l), cat=c(1300l, 1320l, 1325l, 1300l, 1300l, 1325l, 1300l, 1325l), low=c(24.625, 16.250, 14.500, 43.625, 58.250, 45.375, 90.750, 77.875), high=c(26.625, 17.500, 15.500, 45.625, 60.000, 47.375, 92.750, 79.875) ) df id cat low high 1: 18 1300 24.625 26.625 2: 18 1320 16.250 17.500 3: 18 1325 14.500 15.500 4: 46 1300 43.625 45.625 5: 74 1300 58.250 60.000 6: 74 1325 45.375 47.375 7: 165 1300 90.750 92.750 8: 165 1325 77.875 79.875
here, have total of 8 observations of 4 different items (ids 18, 46, 74 , 165). each item recorded in several categories (cat 1300, 1320, 1325) , 2 measurements taken (low , high).
desired output
i want create table each item (id) joins low value of each category (cat) high values of categories that larger via cross join. desired output looks like
id cat cat_large low high 1: 18 1300 1320 24.625 17.500 2: 18 1300 1325 24.625 15.500 3: 18 1320 1325 16.250 15.500 4: 74 1300 1325 58.250 47.375 5: 165 1300 1325 90.750 79.875
where added cat_high indicate 2 categories being joined in low/high.
unfortunately, cannot find correct way amend full cross join, df[,cj(low=low,high=high),by=.(id)]
, behave this. grateful help/hints.
one way:
df[, c( cj(cat = cat, lcat = cat, sorted = false), cj(low = low, high = high, sorted = false) ), by=id][lcat > cat] id cat lcat low high 1: 18 1300 1320 24.625 17.500 2: 18 1300 1325 24.625 15.500 3: 18 1320 1325 16.250 15.500 4: 74 1300 1325 58.250 47.375 5: 165 1300 1325 90.750 79.875
Comments
Post a Comment