Debian Codegraph @

R/contract.R

raw
1 muq <- function(x,sort=FALSE,drop.na=TRUE){
2 u <- unique(x)
3 if(drop.na)
4 u <- na.omit(u)
5 if(sort)
6 u <- sort(u)
7 structure(match(x,u),
8 unique=u)
9 }
10
11 contract <- function(x,...) UseMethod("contract")
12
13 contract.data.frame <- function(x,
14 by=NULL,
15 weights=NULL,
16 name="Freq",
17 force.name=FALSE,
18 sort=FALSE,
19 drop.na=TRUE,
20 ...){
21 w <- NULL
22 if(!missing(by)){
23 tmp <- as.list(seq_along(x))
24 names(tmp) <- names(x)
25 by <- eval(substitute(by),tmp,parent.frame())
26 if(inherits(by,"formula")){
27 if(length(by)>2){
28 w <- eval(by[[2]],x,parent.frame())
29 by <- by[-2]
30 }
31 by <- all.vars(by)
32 }
33 }
34 if(!missing(weights)) {
35 weights <- eval(substitute(weights),x,parent.frame())
36 if(!is.numeric(weights)) stop("'weights' must be numeric")
37 if(length(w) && is.numeric(w)) warning("Ignoring extraneous 'weights' argument")
38 if(!length(w))
39 w <- weights
40 }
41 if(!missing(by))
42 x <- x[by]
43
44 i <- lapply(x,muq,sort=sort,drop.na=drop.na)
45 u <- lapply(i,attr,"unique")
46 l <- sapply(u,length)
47 n <- length(i)
48 j <- i[[1]]
49 if(n > 1){
50 r <- l[1]
51 for(k in 2:n){
52 i.k <- i[[k]]
53 j <- j + r*(i.k-1)
54 j <- muq(j,sort=sort,drop.na=drop.na)
55 r <- length(attr(j,"unique"))
56 }
57 }
58 if(!length(w)){
59 f <- tabulate(j)
60 }
61 else {
62 if(length(w) != nrow(x))
63 stop("'weights' argument has wrong length")
64 if(any(is.na(w)))
65 warning("NA weights treated as zero")
66 if(is.factor(w)){
67 w <- dummyMatrix(w)
68 if(!missing(weights))
69 w <- w*weights
70 }
71 if(drop.na && any(is.na(j))){
72 keep <- !is.na(j)
73 f <- rowsum.default(w[keep],j[keep],na.rm=TRUE)
74 }
75 else
76 f <- rowsum.default(w,j,na.rm=TRUE)
77 }
78 if(drop.na)
79 y <- x[!duplicated(j) & !is.na(j),,drop=FALSE]
80 else
81 y <- x[!duplicated(j),,drop=FALSE]
82 if(sort){
83 uj <- unique(j)
84 y <- y[order(uj),,drop=FALSE]
85 }
86 rownames(y) <- 1:nrow(y)
87 if(NCOL(f) > 1){
88 if(force.name)
89 colnames(f) <- paste(name,colnames(f),sep=".")
90 nms <- c(colnames(y),colnames(f))
91 y <- cbind(y,f)
92 names(y) <- nms
93 }
94 else
95 y[[name]] <- drop(f)
96 y
97 }
98
99 contract.data.set <- contract.data.frame
100
101 dummyMatrix <- function(f){
102 stopifnot(is.factor(f))
103 l <- levels(f)
104 res <- matrix(nrow=length(f),ncol=length(l))
105 for(i in seq_along(l)){
106 res[,i] <- as.integer(f==l[i])
107 }
108 colnames(res) <- l
109 res
110 }