Debian Codegraph @

R/groupwise.R

raw
1 # Some idea, that I did not follow through with ...
2
3 eval.by <- function(f,expr) UseMethod("eval.by")
4 eval.by.default <- function(f,expr){
5 parent <- parent.frame()
6 expr <- substitute(expr)
7 vars <- all.vars(expr)
8 vars <- data.frame(sapply(vars,get,parent))
9 vars <- split(vars,f)
10 res <- lapply(vars,function(v)eval(expr,v,parent))
11 unsplit(res,f)
12 }
13
14 # New stuff
15
16 getRows_ <- function(i,data) {
17 data[i,,drop=FALSE]
18 }
19
20 as_factor <- function(x){
21 if(inherits(x,"item.vector")){
22 x <- include.missings(x)
23 x <- if(is.ordinal(x)) as.ordered(x)
24 else if(is.nominal(x)) as.factor(x)
25 else as.vector(x)
26 }
27 if(!is.factor(x)){
28 lev <- sort(unique(x),na.last=TRUE)
29 i <- match(x,lev)
30 x <- factor(i,labels=as.character(lev))
31 return(x)
32 }
33 else {
34 # if(any(is.na(x))){
35 # lev <- c(levels(x),"<NA>")
36 # nlev <- length(lev)
37 # x <- as.integer(x)
38 # x[is.na(x)] <- nlev
39 # x <- factor(x,labels=lev)
40 # }
41 x <- addNA(factor(x),ifany=TRUE)
42 return(x)
43 }
44 }
45
46 get_all_vars <- function(formula,data,inherits=TRUE){
47 formula.vars <- all.vars(formula)
48 data.vars <- names(data)
49 if(all(formula.vars %in% data.vars))
50 return(data[formula.vars])
51 else {
52 other.vars <- setdiff(formula.vars,data.vars)
53 data.vars <- intersect(formula.vars,data.vars)
54 res <- data[data.vars]
55 other.vars <- mget(other.vars,inherits=inherits)
56 res[names(other.vars)] <- other.vars
57 return(res)
58 }
59 }
60
61 Groups <- function(data,by,...) UseMethod("Groups")
62
63 Groups.data.frame <- function(data,by,...){
64 by.vars <- get_all_vars(by,data)
65 factors <- lapply(by.vars,as_factor)
66 ii <- 1:nrow(data)
67 ii <- tapply(ii,factors,I)
68 n.ii <- sapply(ii,length)
69 dim(n.ii) <- dim(ii)
70 extra.attr <- list(groups=ii,
71 sizes=n.ii,
72 spec=by.vars[0,,drop=FALSE],
73 class=c(paste("grouped",class(data)[1],sep="."),"grouped.data",class(data)))
74 attributes(data) <- c(attributes(data),extra.attr)
75 data
76 }
77
78
79 Groups.data.set <- function(data,by,...){
80 by.vars <- get_all_vars(by,data)
81 factors <- lapply(by.vars,as_factor)
82 data <- structure([email protected],
83 names=names(data),
84 row.names=data@row_names,
85 class="data.frame")
86 ii <- 1:nrow(data)
87 ii <- tapply(ii,factors,I)
88 n.ii <- sapply(ii,length)
89 dim(n.ii) <- dim(ii)
90 extra.attr <- list(groups=ii,
91 sizes=n.ii,
92 spec=by.vars[0,,drop=FALSE],
93 class=c("grouped.data.set","grouped.data",class(data)))
94 attributes(data) <- c(attributes(data),extra.attr)
95 data
96 }
97
98 Groups.grouped.data <- function(data,by,...)Groups(recombine(data),by,...)
99
100 ngroups <- function(x){
101 sum(attr(x,"sizes") > 0)
102 }
103
104 eval1call <- function(data,call,envir){
105 call$data <- data
106 eval(call,envir=envir)
107 }
108
109 mklen <- function(x,n){
110 y <- vector(length=n,mode=mode(x))
111 y[] <- x
112 return(y)
113 }
114
115 first <- function(x) x[[1]]
116 last <- function(x) x[[length(x)]]
117 set_first <- function(x,value){
118 x[[1]] <- value
119 x
120 }
121 set_last <- function(x,value){
122 x[[length(x)]] <- value
123 x
124 }
125
126 fill_dimnames2 <- function(dn,d){
127 isn <- sapply(dn,length) == 0
128 dn[isn] <- lapply(d[isn],seq.int)
129 dn
130 }
131
132 within1.grouped.data <- function(ii,data,expr,N_,parent=parent.frame(),...){
133 if(!length(ii)) return(NULL)
134 encl <- new.env(parent=parent)
135 n <- length(ii)
136 assign("n_",n,envir=encl)
137 assign("N_",N_,envir=encl)
138 assign("i_",ii,envir=encl)
139 e <- evalq(environment(),data[ii,,drop=FALSE],encl)
140 eval(expr,e)
141 l <- as.list(e,all.names=TRUE)
142 # l[!vapply(l, is.null, NA, USE.NAMES = FALSE)]
143 ll <- vapply(l,length,0,USE.NAMES=FALSE)
144 ll1 <- which(ll==1)
145 l[ll1] <- lapply(l[ll1],mklen,n)
146 wrongl <- which(ll != n)
147 l[wrongl] <- NULL
148 return(l)
149 }
150
151 rbind1col <- function(i,mat){
152 do.call(c,mat[,i])
153 }
154
155 reorder1 <- function(x,ii){
156 x[ii] <- x
157 return(x)
158 }
159
160 within.grouped.data <- function(data,expr,recombine=FALSE,...){
161
162 parent <- parent.frame()
163 mc <- match.call()
164
165 groups <- attr(data,"groups")
166 sizes <- attr(data,"sizes")
167 non_empty <- as.vector(sizes) > 0
168 ii <- groups[non_empty]
169
170 av <- all.vars(mc$expr)
171 av <- intersect(av,names(data))
172
173 res <- lapply(ii,within1.grouped.data,data[av],mc$expr,N_=nrow(data),parent=parent.frame())
174
175 n <- length(res)
176 m <- length(res[[1]])
177 nms <- names(res[[1]])
178 res <- unlist(res,recursive=FALSE)
179
180 dim(res) <- c(m,n)
181
182 res <- t(res)
183 res <- lapply(1:m,FUN=rbind1col,mat=res)
184
185 names(res) <- nms
186
187 ii <- unlist(ii)
188
189 res <- lapply(res,FUN=reorder1,ii=ii)
190 res <- rev(res)
191
192 data[names(res)] <- res
193
194 if(recombine)
195 return(recombine(data))
196 else
197 return(data)
198 }
199
200 with1 <- function(ii,data,expr,N_,parent=parent.frame(),...){
201 encl <- new.env(parent=parent)
202 assign("n_",length(ii),envir=encl)
203 assign("N_",N_,envir=encl)
204 assign("i_",ii,envir=encl)
205 eval(expr, data[ii,,drop=FALSE], enclos = encl)
206 }
207
208 add_tags <- function(expr,taggables=c("c","list","cbind","rbind")){
209 is_taggable <- as.character(expr[[1]]) %in% taggables
210 if(is_taggable){
211 expr_1 <- expr[-1]
212 n <- length(expr_1)
213 if(!length(names(expr_1))){
214 untagged <- rep(TRUE,n)
215 names(expr) <- c("",letters[seq.int(n)])
216 }
217 else
218 untagged <- !nzchar(names(expr_1))
219 if(any(untagged)){
220 names(expr)[-1][untagged] <- sapply(expr_1[untagged],deparse)
221 }
222 }
223 expr
224 }
225
226 with.grouped.data <- function(data,expr,...){
227 mc <- match.call()
228 expr <- mc$expr
229 groups <- attr(data,"groups")
230 sizes <- attr(data,"sizes")
231 non_empty <- as.vector(sizes) > 0
232 av <- all.vars(mc$expr)
233 av <- intersect(av,names(data))
234 #with1. <- function(ii) eval(mc$expr,data[ii,av,drop=FALSE],enclos=parent.frame())
235 expr <- add_tags(expr)
236
237 ii <- groups[non_empty]
238 res_ <- lapply(ii,with1,data[av],expr,N_=nrow(data),parent=parent.frame())
239 #system.time(res_ <- lapply(ii,with1.))#,data[av],mc$expr)
240 spec_ <- attr(data,"spec")
241
242 res_len <- sapply(res_,length)
243
244 if(length(unique(res_len))==1) {
245 # All results have the same length
246 res_len <- res_len[1]
247 if(length(dim(res_[[1]]))){
248 dim_res <- dim(res_[[1]])
249 newdim <- c(dim_res,dim(groups))
250 if(length(res_dimnames <- dimnames(res_[[1]]))){
251 newdimnames <- c(res_dimnames,dimnames(groups))
252 }
253 else
254 newdimnames <- c(rep(list(NULL),length(dim_res)),
255 dimnames(groups))
256 } else if(length(res_[[1]]) > 1){
257 newdim <- c(length(res_[[1]]),dim(groups))
258 newdimnames <- c(list(names(res_[[1]])),dimnames(groups))
259 } else {
260 newdim <- dim(groups)
261 newdimnames <- dimnames(groups)
262 }
263 if(all(sapply(res_,is.atomic))) {
264 if(all(non_empty)){
265 res <- unlist(res_)
266 }
267 else {
268 res <- rep(NA,length(groups)*res_len)
269 res[rep(non_empty,each=res_len)] <- unlist(res_)
270 }
271
272 } else {
273 res <- vector(mode="list",length=length(groups)*res_len)
274 res[rep(non_empty,each=res_len)] <- unlist(res_,recursive=FALSE)
275 }
276 dim(res) <- newdim
277 dimnames(res) <- fill_dimnames2(newdimnames,newdim)
278 }
279 else {
280 res <- vector(mode="list",length=length(groups))
281 res[non_empty] <- unlist(res_,recursive=FALSE)
282 dim(res) <- dim(groups)
283 dimnames(res) <- dimnames(groups)
284 }
285
286 if(length(dim(res)) >= 2){
287 if(is.null(rownames(res))){
288 if(nrow(res)==1) rownames(res) <- deparse(expr)
289 else if( as.character(expr[[1]]) %in% c("c","cbind","rbind")
290 && length(expr[-1]) == nrow(res))
291 rownames(res) <- paste(expr[-1])
292 else if(as.character(expr[[1]]) %in% c("range"))
293 rownames(res) <- c("Min","Max")
294 }
295 }
296
297 class(res) <- "grouped.result"
298 attr(res,"spec") <- spec_
299 attr(res,"sizes") <- sizes
300 if(is.atomic(res))
301 class(res) <- c(class(res),"table")
302 res
303 }
304
305 print.grouped.result <- function(x,...){
306 attr(x,"spec") <- NULL
307 attr(x,"sizes") <- NULL
308 class(x) <- NULL #setdiff(class(x),"grouped.result")
309 print.default(x)
310 }
311
312 withGroups <- function(data,by,expr,...) {
313 data <- Groups(data=data,by=by)
314 call_ <- match.call()
315 call_[[1]] <- with.grouped.data
316 call_$data <- data
317 eval(call_,envir=parent.frame())
318 }
319 withinGroups <- function(data,by,expr,recombine=TRUE,...) {
320 data <- Groups(data=data,by=by)
321 call_ <- match.call()
322 call_[[1]] <- within
323 call_$data <- data
324 call_$recombine <- recombine
325 eval(call_,envir=parent.frame())
326 }
327
328 recombine <- function(x,...) UseMethod("recombine")
329
330 recombine.grouped.data.frame <- function(x,...) {
331 attributes(x)[c("spec","sizes","groups")] <- NULL
332 class(x) <- "data.frame"
333 return(x)
334 }
335
336 recombine.grouped.data.set <- function(x,...) {
337 attributes(x)[c("spec","sizes","groups")] <- NULL
338 class(x) <- NULL
339 return(new("data.set",x))
340 }
341
342
343 print.grouped.data.frame <- function(x,...){
344 ngrps <- ngroups(x)
345 cat("\nGrouped data frame with",nrow(x), "observations in",ngrps,"groups of",ncol(x),"variables\n\n")
346 print_frame_internal(x,max.obs=getOption("show.max.obs"),width=getOption("width"),...)
347 }
348
349 print.grouped.data.set <- function(x,...){
350 ngrps <- ngroups(x)
351 cat("\nGrouped data frame with",nrow(x), "observations in",ngrps,"groups of",ncol(x),"variables\n\n")
352 print_frame_internal(x,max.obs=getOption("show.max.obs"),width=getOption("width"),...)
353 }
354
355
356 as.data.set.grouped.data <- function(x,...){
357 as.data.set(recombine(x),...)
358 }
359
360 as.data.frame.grouped.data <- function(x,...){
361 as.data.frame(recombine(x),...)
362 }
363
364 setOldClass("grouped.data.set")
365 setOldClass("grouped.data.frame")
366 setMethod("as.data.set","grouped.data.set",as.data.set.grouped.data)
367 setMethod("as.data.set","grouped.data.frame",as.data.set.grouped.data)