set.seed(45)
require(reshape2)
require(data.table)
DT <- data.table(
i1 = c(1:5, NA),
i2 = c(NA,6,7,8,9,10),
f1 = factor(sample(c(letters[1:3], NA), 6, TRUE)),
c1 = sample(c(letters[1:3], NA), 6, TRUE),
d1 = as.Date(c(1:3,NA,4:5), origin="2013-09-01"),
d2 = as.Date(6:1, origin="2012-01-01"))
DT[, l1 := DT[, list(c=list(rep(i1, sample(5,1)))), by = i1]$c] # list cols
DT[, l2 := DT[, list(c=list(rep(c1, sample(5,1)))), by = i1]$c]
# basic examples
melt(DT, id=1:2, measure=3)
melt(DT, id=c("i1", "i2"), measure="f1", value.factor=TRUE) # same as above, but value is factor
# on Date
melt(DT, id=c("i1", "f1"), measure=c("d1", "d2")) # date class attribute lost
melt(DT, id=c("i1", "f1"), measure=c("c1", "d1")) # value is char, date attribute lost
# on list
melt(DT, id=1, measure=c("l1", "l2")) # value is a list
melt(DT, id=1, measure=c("c1", "l1")) # c1 coerced to list
# on character
melt(DT, id=1, measure=c("c1", "f1")) # value is char
melt(DT, id=1, measure=c("c1", "i2")) # i2 coerced to char
# on na.rm=TRUE
melt(DT, id=1, measure=c("c1", "i2"), na.rm=TRUE) # remove NA
Run the code above in your browser using DataLab