Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- library(foreach)
- library(iterators)
- library(data.table)
- library(pipeR)
- set.seed(10)
- k <- 1
- outList <- foreach(v = iter(matrix(sample(3:29, 6000, TRUE), 1000), by = "row")) %:% when(k <= 4) %do%
- {
- if (all(diff(sort(v)) > 2)) {
- k <- k + 1
- return(data.table(studentID = k, matrix(c(1, sort(v), 31), 4, 2, TRUE, list(NULL, c("Start", "End")))))
- } else return(NULL)
- }
- outDT <- rbindlist(outList) %>>% `[`(j = `:=`(studentID = match(studentID, sort(unique(studentID))),
- avgScore = abs(rnorm(nrow(.)))))
- # studentID Start End avgScore
- # 1: 1 1 3 0.4605151
- # 2: 1 6 10 0.2350253
- # 3: 1 19 22 0.6432573
- # 4: 1 25 31 0.9131981
- # 5: 2 1 4 0.9882860
- # 6: 2 7 11 0.1127413
- # 7: 2 16 20 1.4900499
- # 8: 2 26 31 0.4432356
- # 9: 3 1 5 1.3623441
- # 10: 3 10 14 1.0452357
- # 11: 3 21 25 0.2339315
- # 12: 3 28 31 2.5524180
- # 13: 4 1 4 1.7687187
- # 14: 4 7 10 0.6595706
- # 15: 4 19 23 0.3707332
- # 16: 4 26 31 0.5928033
- iter <- isplit(outDT, outDT$studentID)
- resDT <- copy(iter$nextElem()$value) %>>% `[`(j = `:=`(studentID = NULL))
- setkey(resDT, Start, End)
- while (TRUE) {
- v <- tryCatch(iter$nextElem(), error = function(e) e)
- if (any(class(v) == "error"))
- break
- resDT <- foverlaps(v$value, resDT, type = "any", nomatch = 0) %>>%
- `[`(j = `:=`(Start = pmax(Start, i.Start), End = pmin(End, i.End))) %>>%
- `[`(j = .(Start, End))
- setkey(resDT, Start, End)
- }
- # Start End
- # 1: 1 3
- # 2: 10 10
- # 3: 28 31
- finalResDT <- foreach(it = isplit(outDT, outDT$studentID), .final = rbindlist) %do%
- {
- foverlaps(it$value, resDT, type = "any", nomatch = 0) %>>%
- `[`(j = avgScore := (i.End - End + 1) / (Start - i.Start + 1) * avgScore) %>>%
- `[`(j = .(Start, End, studentID, avgScore))
- } %>>% dcast(Start + End ~ studentID, val.var = "avgScore") %>>%
- setnames(as.character(1:(ncol(.)-2)), paste0("studentID-", 1:(ncol(.)-2)))
- # Start End studentID-1 studentID-2 studentID-3 studentID-4
- # 1: 1 3 0.46051506 1.97657201 4.087032 3.5374375
- # 2: 10 10 0.04700506 0.05637067 5.226179 0.1648927
- # 3: 28 31 0.22829953 0.14774520 2.552418 0.1976011
Advertisement
Add Comment
Please, Sign In to add comment