1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| extendTbl <- function(DT, unnestCols = NULL){ if (is.null(unnestCols)) { unnestCols <- names(DT)[sapply(DT, function(x) any(class(x) %in% "list"))] message("Automatically recognize the nested columns: ", paste0(unnestCols, collapse = ", ")) } if (any(!unnestCols %in% names(DT))) stop(sprintf("The columns, %s, does not in the DT.", paste0(unnestCols[!unnestCols %in% names(DT)], collapse = ", "))) groupbyVar <- setdiff(names(DT), unnestCols) chkExpr <- paste0(groupbyVar, "=NULL", collapse = ",") %>>% (paste0("`:=`(", ., ")")) chkLenAllEqual <- DT[ , lapply(.SD, function(x) sapply(x, length)), by = groupbyVar] %>>% `[`(j = eval(parse(text = chkExpr))) %>>% as.matrix %>>% apply(1, diff) %>>% `==`(0) %>>% all if (!chkLenAllEqual) stop("The length in each cell is not equal.")
expr <- unnestCols %>>% (paste0(., "=unlist(", ., ")")) %>>% paste0(collapse = ",") %>>% (paste0(".(", ., ")")) return(DT[ , eval(parse(text = expr)), by = groupbyVar]) } extendTbl(DT)
extendTbl(DT, c("b", "d"))
|