require(data.table)
names(ChickWeight) <- tolower(names(ChickWeight))
DT <- melt(as.data.table(ChickWeight), id=2:4) # calls melt.data.table
# dcast is a S3 method in data.table from v1.9.6
dcast(DT, time ~ variable, fun=mean)
dcast(DT, diet ~ variable, fun=mean)
dcast(DT, diet+chick ~ time, drop=FALSE)
dcast(DT, diet+chick ~ time, drop=FALSE, fill=0)
# using subset
dcast(DT, chick ~ time, fun=mean, subset=.(time < 10 & chick < 20))
## Not run:
# # benchmark against reshape2's dcast, minimum of 3 runs
# set.seed(45)
# DT <- data.table(aa=sample(1e4, 1e6, TRUE),
# bb=sample(1e3, 1e6, TRUE),
# cc = sample(letters, 1e6, TRUE), dd=runif(1e6))
# system.time(dcast(DT, aa ~ cc, fun=sum)) # 0.12 seconds
# system.time(dcast(DT, bb ~ cc, fun=mean)) # 0.04 seconds
# # reshape2::dcast takes 31 seconds
# system.time(dcast(DT, aa + bb ~ cc, fun=sum)) # 1.2 seconds
# ## End(Not run)
# NEW FEATURE - multiple value.var and multiple fun.aggregate
dt = data.table(x=sample(5,20,TRUE), y=sample(2,20,TRUE),
z=sample(letters[1:2], 20,TRUE), d1 = runif(20), d2=1L)
# multiple value.var
dcast(dt, x + y ~ z, fun=sum, value.var=c("d1","d2"))
# multiple fun.aggregate
dcast(dt, x + y ~ z, fun=list(sum, mean), value.var="d1")
# multiple fun.agg and value.var (all combinations)
dcast(dt, x + y ~ z, fun=list(sum, mean), value.var=c("d1", "d2"))
# multiple fun.agg and value.var (one-to-one)
dcast(dt, x + y ~ z, fun=list(sum, mean), value.var=list("d1", "d2"))
Run the code above in your browser using DataLab