r - Melt data.table according to nested list -
i had data.table this:
library(data.table) dt <- data.table(a = c(rep("a", 3), rep("b", 3)), b = c(1, 3, 5, 2, 4, 6))
i needed perform operation (forecast) on values each a
, decided put them in list, this:
dt <- dt[, x := .(list(b)), = a][, .sd[1,], = a, .sdcols = "x"]
now wanted "melt" (that's thing comes mind) dt
original form.
i few levels of a
this:
dt2 <- rbind(expand.grid(dt[1, a], dt[1, x[[1]]]), expand.grid(dt[2, a], dt[2, x[[1]]]))
but of course, solution impractical more levels of a
.
i've tried
dt2 <- dt[, expand.grid(a, x[[1]]), = a]
which results in
dt2 ## var1 var2 ## 1: 1 ## 2: 3 ## 3: 5 ## 4: b 2 ## 5: b 4 ## 6: b 6
it's interesting notice var1
doesn't follow "a - b" pattern expected (but @ least a
remains).
is there better approach achieve this?
edits
expected output result of
dt2[, .(a, var2)]
- corrected "melt" "dcast".
you looking method nest
(convert column atomic vector type list type) , unnest
(the opposite direction) in data.table way. different reshaping data either spread
column values row header(dcast
) or gather
row headers column values(melt
):
in data.table syntax, can use list
, unlist
on target column summarize or broadcast along group variables:
say if starting from:
dt # b # 1: 1 # 2: 3 # 3: 5 # 4: b 2 # 5: b 4 # 6: b 6
to repeat have achieved in first step, i.e. nest
column b
, can do:
dt_nest <- dt[, .(b = list(b)), a] dt_nest # b # 1: 1,3,5 # 2: b 2,4,6
to go opposite direction, use unlist
group variable:
dt_nest[, .(b = unlist(b)), a] # b # 1: 1 # 2: 3 # 3: 5 # 4: b 2 # 5: b 4 # 6: b 6
Comments
Post a Comment