1### wideByFactor.R
2###------------------------------------------------------------------------
3### What: Reshape by factor levels - code
4### $Id$
5### Time-stamp: <2008-12-30 22:17:32 ggorjan>
6###------------------------------------------------------------------------
7
8wideByFactor <- function(x, factor, common, sort=TRUE, keepFactor=TRUE)
9{
10  ## --- Setup ---
11  if(!is.data.frame(x)) stop("'x' must be a data frame")
12  if(length(factor) != 1) stop("'factor' can be only of length one")
13  if(!is.factor(x[[factor]])) stop("column defined in 'factor' must be a factor")
14  if(sort) x <- x[order(x[[factor]]), ]
15
16  ## --- Extend by factors levels ---
17  y <- x[common]
18  if(keepFactor) y[factor] <- x[factor]
19  levs <- levels(x[[factor]])
20
21  ## Remove common and factor from the list of column names
22  other <- names(x)
23  other <- other[!(other %in% common) & !(other %in% factor)]
24
25  ## Add all other columns but as a set for each level of a factor
26  for(level in levs) {
27    for(col in other) {
28      ## add a column col
29      y[paste(col, level, sep=".")] <- x[col]
30      ## fill with NA for other levels than level
31      y[x[factor] != level, paste(col, level, sep=".")] <- NA
32      ## This filling migth be inefficient if there is large number
33      ## of levels, since there will be quite a lot of filling.
34    }
35  }
36  y
37}
38
39###------------------------------------------------------------------------
40### wideByFactor.R ends here