R/Working with Data Frames

From QERM Wiki
Jump to: navigation, search

Creating parameter combinations

If you need to create a data frame with all possible combinations of several parameters, expand.grid is very helpful:

a = 1:5
b = c(10, 20)
c = c("above", "below", "middle")
params = expand.grid(a = a, b= b, c = c)

Reshape three column data frame to matrix

This stackoverflow question is a great reference of ways to do this. A couple of examples copied below.

tmp <- data.frame(x=gl(2,3, labels=letters[24:25]),
                  y=gl(3,1,6, labels=letters[1:3]), 
                  z=c(1,2,3,3,3,2))

Using reshape2:

library(reshape2)
acast(tmp, x~y, value.var="z")

Using matrix indexing:

with(tmp, {
  out <- matrix(nrow=nlevels(x), ncol=nlevels(y),
                dimnames=list(levels(x), levels(y)))
  out[cbind(x, y)] <- z
  out
})

Using xtabs:

xtabs(z~x+y, data=tmp)
Personal tools