Debian Codegraph @

R/importer-methods.R

raw
1 setMethod("as.data.set","importer",function(x,row.names=NULL,optional=NULL,
2 compress.storage.modes=FALSE,...){
3 seekData(x)
4 res <- readData(x,n=nrow(x))
5 if(compress.storage.modes)
6 res <- lapply(res,function(x){
7 [email protected] <- compress.storage.mode([email protected])
8 cl.x <- paste(storage.mode([email protected]),"item",sep=".")
9 attr(cl.x,"package") <- attr(class(x),"package")
10 class(x) <- cl.x
11 x
12 })
13 names(res) <- names(x)
14 class(res) <- "data.frame"
15 if(length(row.names)){
16 if(length(row.names)!=nrow(x)) stop("row.names argument has wrong length")
17 attr(res,"row.names") <- row.names
18 }
19 else
20 attr(res,"row.names") <- seq_len(nrow(x))
21 new("data.set",res)
22 })
23
24
25 setMethod("dim","importer",function(x){
26 c(getNobs(x),length([email protected]))
27 })
28
29 # setMethod("names","importer",function(x)names(x@frame))
30
31
32 bracket.importer <- function(x,Nargs,i,j,drop=TRUE,compress.storage.modes=FALSE,...){
33 mycall <- match.call()
34 mspl <- missing(compress.storage.modes)
35 mdrp <- missing(drop)
36 #Nargs <- Nargs - (!mdrp) - (!mspl) - length(list(...))
37
38 ncases <- nrow(x)
39 names <- names(x)
40 nvar <- length(names)
41
42 # browser()
43 # message("Nargs = ",Nargs)
44
45 if(Nargs == 1){
46 if(missing(i)) return(as.data.set(x))
47 if(is.array(i)) stop("index arrays not supported")
48 j <- i
49 i <- rep(TRUE,ncases)
50 }
51 else{
52 if(missing(i)){
53 i <- rep(TRUE,ncases)
54 }
55 if(missing(j)){
56 j <- rep(TRUE,nvar)
57 }
58 }
59
60 if(is.logical(i)){
61 rows <- i
62 ui <- which(i)
63 row.nums <- ui
64 } else if(is.numeric(i)){
65 i <- as.integer(i)
66 row.nums <- i
67 ui <- sort(unique(i))
68 rows <- logical(max(ui))
69 rows[ui] <- TRUE
70 }
71 else stop("mode ",sQuote(mode(i))," not supported for row selection")
72
73 if(is.logical(j)){
74 cols <- j
75 } else if(is.numeric(j)){
76 if(max(j)>nvar) stop("undefined columns selected")
77 cols <- logical(nvar)
78 cols[j] <- TRUE
79 } else if(is.character(j)){
80 if(!all(j %in% names)) stop("undefined columns selected")
81 cols <- names %in% j
82 } else stop("mode ",sQuote(mode(i))," not supported for column selection")
83
84 seekData(x)
85 if(length(rows) > nrow(x)) length(rows) <- nrow(x)
86 res <- readSlice(x,rows,cols)
87 if(compress.storage.modes)
88 res <- lapply(res,function(x){
89 [email protected] <- compress.storage.mode([email protected])
90 cl.x <- paste(storage.mode([email protected]),"item",sep=".")
91 attr(cl.x,"package") <- attr(class(x),"package")
92 class(x) <- cl.x
93 x
94 })
95 names(res) <- names[cols]
96 class(res) <- "data.frame"
97 if(is.numeric(i)){
98 ii <- match(i,ui)
99 res <- res[ii,,drop=FALSE]
100 }
101 attr(res,"row.names") <- as.integer(row.nums)
102 if(drop && length(res)==1) res[[1]]
103 new("data.set",res)
104 }
105
106 setMethod("[",signature(x="importer",i="atomic",j="atomic",drop="ANY"),
107 function(x,i,j,...,drop=TRUE)
108 bracket.importer(x,Nargs=nargs()-1-(!missing(drop))-length(list(...)),i,j,drop=drop,...)
109 )
110 setMethod("[",signature(x="importer",i="atomic",j="missing",drop="ANY"),
111 function(x,i,j,...,drop=TRUE)
112 bracket.importer(x,Nargs=nargs()-1-(!missing(drop))-length(list(...)),i,j,drop=drop,...)
113 )
114 setMethod("[",signature(x="importer",i="missing",j="atomic",drop="ANY"),
115 function(x,i,j,...,drop=TRUE)
116 bracket.importer(x,Nargs=nargs()-1-(!missing(drop))-length(list(...)),i,j,drop=drop,...)
117 )
118 setMethod("[",signature(x="importer",i="missing",j="missing",drop="ANY"),
119 function(x,i,j,...,drop=TRUE)
120 bracket.importer(x,Nargs=nargs()-1-(!missing(drop))-length(list(...)),i,j,drop=drop,...)
121 )
122
123 c_Data <- function(x1,x2) {
124 if(is.null(x1)) return(x2)
125 else {
126 y <- x1
127 [email protected] <- c([email protected],[email protected])
128 return(y)
129 }
130 }
131
132 subset.importer <- function (x, subset, select, drop = FALSE,
133 ...){
134
135 if(missing(subset) && missing(select))
136 return(as.data.set(x))
137
138 nobs <- nrow(x)
139 names <- names(x)
140 nvars <- length(names)
141 cs <- getOption("subset.chunk.size",nobs)
142 if(cs < 1) stop("'subset.chunk.size' option must be a positive integer or NULL")
143
144 if(missing(select)){
145 cols <- rep(TRUE,nvars)
146 select.vars <- names(x)
147 }
148 else {
149 nl <- as.list(1:nvars)
150 names(nl) <- names
151 cols <- logical(nvars)
152 if (is.call(substitute(select))) {
153 cols[eval(substitute(select), nl, parent.frame())] <- TRUE
154 select.vars <- sapply(substitute(select)[-1],as.character)
155 } else { # As suggested by Diogo Ferrari (https://dioferrari.com/)
156 select.vars <- select
157 cols[which(names(nl) %in% select.vars )] <- TRUE
158 }
159
160 }
161 if(nobs < cs) cs <- nobs
162 m <- nobs %/% cs
163 r <- nobs %% cs
164
165 seekData(x)
166 if(missing(subset)){
167 res <- readChunk(x,nrows=nobs,cols=cols)
168 names(res) <- names(x)[cols]
169 res <- res[select.vars]
170 attr(res,"row.names") <- 1:nobs
171 }
172 else {
173 select.cols <- cols
174 e <- substitute(subset)
175 subset.vars <- all.vars(e)
176 subset.cols <- names(x) %in% subset.vars
177 cols <- select.cols | subset.cols
178 chunk.names <- names(x)[cols]
179 chunk.cols <- chunk.names %in% select.vars
180 res <- [email protected][select.cols]
181 res.nobs <- 0
182 row.nums <- integer(0)
183 nobs.visited <- 0
184 for(i in 1:m){
185 chunk <- readChunk(x,nrows=cs,cols=cols)
186 names(chunk) <- chunk.names
187 use.obs <- eval(e,chunk,parent.frame())
188 if(!is.logical(use.obs)) stop("non-logical subset arg")
189 if(any(use.obs)){
190 res.nobs <- res.nobs + sum(use.obs)
191 chunk <- chunk[chunk.cols]
192 chunk <- lapply(chunk,"[",use.obs)
193 res <- mapply(c_Data,res,chunk,SIMPLIFY=FALSE)
194 row.nums.i <- seq.int(cs)[use.obs]
195 row.nums.i <- nobs.visited + row.nums.i
196 row.nums <- c(row.nums,row.nums.i)
197 }
198 nobs.visited <- nobs.visited + cs
199 }
200 if(r > 0){
201 chunk <- readChunk(x,nrows=r,cols=cols)
202 names(chunk) <- chunk.names
203 use.obs <- eval(e,chunk,parent.frame())
204 if(!is.logical(use.obs)) stop("non-logical subset arg")
205 if(any(use.obs)){
206 res.nobs <- res.nobs + sum(use.obs)
207 chunk <- chunk[chunk.cols]
208 chunk <- lapply(chunk,"[",use.obs)
209 res <- mapply(c_Data,res,chunk,SIMPLIFY=FALSE)
210 row.nums.i <- seq.int(r)[use.obs]
211 row.nums.i <- nobs.visited + row.nums.i
212 row.nums <- c(row.nums,row.nums.i)
213 }
214 nobs.visited <- nobs.visited + r
215 }
216 stopifnot(nobs.visited == nobs)
217 for(j in 1:length(res)){
218 attributes(res[[j]]) <- attributes(chunk[[j]])
219 }
220 names(res) <- names(x)[select.cols]
221 res <- res[select.vars]
222 attr(res,"row.names") <- as.integer(row.nums)
223 }
224 new.names <- names(select.vars)
225 if(length(new.names) && any(nzchar(new.names))){
226 names.res <- names(res)
227 names.res[nzchar(new.names)] <- new.names[nzchar(new.names)]
228 names(res) <- names.res
229 }
230 class(res) <- "data.frame"
231 new("data.set",res)
232 }
233
234
235 setMethod("$",signature(x="importer"),
236 function(x,name){
237 x[name]
238 })
239
240 setMethod("[[",signature(x="importer"),
241 function(x,i,...){
242 x[i]
243 })
244
245
246 setMethod("description","importer",function(x){
247 res <- lapply(structure([email protected],
248 names=x@names),
249 description)
250 structure(res,class="descriptions")
251 })
252
253 setMethod("codebook","importer",function(x, weights=NULL, unweighted=TRUE, ...){
254 if(!missing(weights))
255 weights <- deparse(substitute(weights))
256 if(length(weights)){
257 cat("Weights are from ",weights,"\n")
258 # warning("Weights for codebooks of 'importer' objects are not yet supported.")
259 }
260
261 cs <- getOption("codebook.chunk.size")
262 nobs <- nrow(x)
263 if(nobs < cs) cs <- nobs
264 m <- nobs %/% cs
265 r <- nobs %% cs
266 nvar <- ncol(x)
267 res <- lapply(structure([email protected],
268 names=x@names),
269 initcodebookEntry)
270 seekData(x)
271 w <- NULL
272 w.idx <- match(weights,names(x))
273 for(i in 1:m){
274 chunk <- readData(x,n=cs)
275 if(length(weights)){
276 w <- as.numeric(chunk[[w.idx]])
277 w[is.na(w)] <- 0
278 }
279 res <- mapply(updatecodebookEntry,res,chunk,
280 MoreArgs=list(weights=w))
281 }
282 if(r > 0){
283 chunk <- readData(x,n=r)
284 if(length(weights)){
285 w <- as.numeric(chunk[[w.idx]])
286 w[is.na(w)] <- 0
287 }
288 res <- mapply(updatecodebookEntry,res,chunk,
289 MoreArgs=list(weights=w))
290 }
291 res <- lapply(res,fixupcodebookEntry,unweighted=unweighted)
292 new("codebook",res)
293 })
294
295 initcodebookEntry <- function(x,weighted){
296 annotation <- annotation(x)
297 filter <- [email protected]
298 spec <- c(
299 "Storage mode:"=storage.mode(x),
300 "Measurement:"=measurement(x)
301 )
302 if(length(filter)) spec <- c(spec,
303 switch(class(filter),
304 missing.values = c("Missing values:" = format(filter)),
305 valid.values = c("Valid values:" = format(filter)),
306 valid.range = c("Valid range:" = format(filter))
307 ))
308 stats <- switch(spec["Measurement:"],
309 nominal=,ordinal=initcodebookStatsCateg(x,weights),
310 interval=,ratio=initcodebookStatsMetric(x,weights),
311 `Date/time`=initcodebookStatsDatetime(x)
312 )
313 new("codebookEntry",
314 spec = spec,
315 stats = stats,
316 annotation = annotation
317 )
318 }
319
320
321 updatecodebookEntry <- function(cbe,x,weights=NULL){
322 switch(cbe@spec["Measurement:"],
323 nominal=,ordinal=updatecodebookStatsCateg(cbe,x,weights),
324 interval=,ratio=updatecodebookStatsMetric(cbe,x,weights),
325 `Date/time`=updatecodebookStatsDatetime(cbe,x)
326 )
327 }
328
329
330 initcodebookStatsCateg <- function(x,weights=NULL) {
331 vl <- labels(x)
332 ic <- inherits(x,"character")
333 if(length(vl) || !ic){
334 if(length(weights))
335 list(tab=list(),wtab=list())
336 else
337 list(tab=list())
338 } else {
339 list()
340 }
341
342 }
343
344 updatecodebookStatsCateg <- function(cbe,x,weights=NULL){
345 vl <- labels(x)
346 ic <- inherits(x,"character")
347 stats <- cbe@stats
348
349 if(length(vl) || !ic){
350 tab <- codebookTable_item(x,drop.empty=FALSE)
351 tab.title <- attr(tab,"title")
352 if(length(stats$tab)){
353 stats$tab <- stats$tab + tab
354 }
355 else
356 stats$tab <- tab
357 attr(stats$tab,"title") <- tab.title
358 if(length(weights)){
359 wtab <- codebookTable_item(x,weights=weights,drop.empty=FALSE)
360 if(length(stats$wtab))
361 stats$wtab <- stats$wtab + wtab
362 else
363 stats$wtab <- wtab
364 }
365 } else {
366 stats1 <- cbChar1(x)
367 stats <- update_cbChar1(stats,stats1)
368 }
369
370 cbe@stats <- stats
371 cbe
372 }
373
374 cbChar1 <- function(x){
375 isna <- is.na(x)
376 NAs <- sum(isna)
377 descr <- structure(range(x),names=c("Min","Max"))
378 list(descr=descr,
379 NAs = NAs)
380 }
381
382 update_cbChar1 <- function(current,update){
383 if(!length(current)) return(update)
384 else {
385 descr <- range(c(current$descr,update$descr))
386 names(descr) <- c("Min","Max")
387 list(
388 descr = as.matrix(descr),
389 NAs = current$NAs + update$NAs
390 )
391 }
392 }
393
394
395 initcodebookStatsMetric <- function(x,weights=NULL){
396 if(length(labels(x))){
397 if(length(weights))
398 stats <- list(tab=list(),wtab=list())
399 else
400 stats <- list(tab=list())
401 }
402 else stats <- list()
403 stats$descr <- numeric(0)
404 stats$range <- numeric(0)
405 stats$missings <- integer(0)
406 stats
407 }
408
409 cb_descr <- function(x,w=NULL){
410 m <- c(n = length(x),
411 sum.x = sum(x),
412 sum.x2 = sum(x^2))
413 if(length(w)){
414 wm <- c(sum(w),
415 sum(w*x),
416 sum(w*x^2))
417 m <- cbind(Unweighted=m,Weighted=wm)
418 }
419 else m <- as.matrix(m)
420 return(m)
421 }
422
423 updatecodebookStatsMetric <- function(cbe,x,weights=NULL){
424 stats <- cbe@stats
425 if(length([email protected])){
426 tab <- codebookTable_item(x,drop.empty=FALSE)
427 tab.title <- attr(tab,"title")
428 if(length(stats$tab)){
429 stats$tab <- stats$tab + tab
430 }
431 else
432 stats$tab <- tab
433 attr(stats$tab,"title") <- tab.title
434 if(length(weights)){
435 wtab <- codebookTable_item(x,weights=weights,drop.empty=FALSE)
436 if(length(stats$wtab))
437 stats$wtab <- stats$wtab + wtab
438 else
439 stats$wtab <- wtab
440 }
441 }
442 ismiss <- is.missing(x)
443 isna <- is.na([email protected])
444 x <- [email protected][!ismiss & !isna]
445 NAs <- sum(isna)
446 miss <- sum(ismiss,na.rm=TRUE)
447 if(length(x)){
448 if(length(weights))
449 w <- weights[!ismiss & !isna]
450 else
451 w <- NULL
452 descr <- cb_descr(x,w=w)
453 stats$descr <- if(length(stats$descr)) stats$descr + descr
454 else descr
455
456 stats$range <- if(length(stats$range)) range(stats$range,range(x))
457 else range(x)
458 }
459 stats$missings <- if(length(stats$missings)) stats$missings + c(miss,NAs)
460 else c(miss,NAs)
461 cbe@stats <- stats
462 cbe
463 }
464
465 initcodebookStatsDatetime <- function(x){
466 stats <- list()
467 stats$moments <- numeric(0)
468 stats$range <- numeric(0)
469 stats$missings <- integer(0)
470 stats
471 }
472
473
474 updatecodebookStatsDatetime <- function(cbe,x,weights=NULL){
475 stats <- cbe@stats
476 miss <- is.missing(x)
477 NAs <- is.na([email protected])
478 x <- [email protected][!miss & !NAs]
479 NAs <- sum(NAs)
480 miss <- sum(miss,na.rm=TRUE)
481 if(length(x)){
482 stats$range <- if(length(stats$range)) range(stats$range,range(x))
483 else range(x)
484 }
485 stats$missings <- if(length(stats$missings)) stats$missings + c(miss,NAs)
486 else c(miss,NAs)
487 cbe@stats <- stats
488 cbe
489 }
490
491
492 fixupcodebookEntry <- function(cbe,unweighted=TRUE){
493 switch(cbe@spec["Measurement:"],
494 nominal=,ordinal=fixupcodebookEntryCateg(cbe,unweighted=unweighted),
495 interval=,ratio=fixupcodebookEntryMetric(cbe,unweighted=unweighted),
496 `Date/time`=fixupcodebookEntryDatetime(cbe)
497 )
498 }
499
500 prc <- function(x){
501 s <- sum(x,na.rm=TRUE)
502 100*x/s
503 }
504
505 fixupcodebookEntryCateg <- function(cbe,unweighted=TRUE){
506 tab <- cbe@stats$tab
507 wtab <- cbe@stats$wtab
508 if(length(tab)){
509 tab.title <- attr(tab,"title")
510 if(length(wtab)){
511 if(unweighted)
512 tab <- collect(Unweighted=tab,
513 Weighted=wtab)
514 else
515 tab <- array(wtab,
516 dim=c(dim(tab),1),
517 dimnames=c(dimnames(tab),
518 list(NULL)))
519 } else {
520 tab <- array(tab,
521 dim=c(dim(tab),1),
522 dimnames=c(dimnames(tab),
523 list(NULL)))
524 }
525 rn <- rownames(tab)
526 ii <- (grepl("(unlab.val.)",rn,fixed=TRUE) | grepl("(unlab.mss.)",rn,fixed=TRUE) |
527 grepl("NA M ",rn,fixed=TRUE))
528 ii <- ii & tab[,1,1] == 0
529 tab <- tab[!ii,,,drop=FALSE]
530 d <- dim(tab)
531 dn <- dimnames(tab)
532 tab[,-1,] <- apply(tab[,-1,,drop=FALSE],2:3,prc)
533 dim(tab) <- d
534 dimnames(tab) <- dn
535 attr(tab,"title") <- tab.title
536 cbe@stats <- list(tab=tab)
537 }
538 cbe
539 }
540
541 fixupcodebookEntryMetric <- function(cbe,unweighted=TRUE){
542 stats <- cbe@stats
543 tab <- stats$tab
544 wtab <- stats$wtab
545 if(length(tab)){
546 tab.title <- attr(tab,"title")
547 if(length(wtab)){
548 if(unweighted)
549 tab <- collect(Unweighted=tab,
550 Weighted=wtab)
551 else
552 tab <- array(wtab,
553 dim=c(dim(tab),1),
554 dimnames=c(dimnames(tab),
555 list(NULL)))
556 } else {
557 tab <- array(tab,
558 dim=c(dim(tab),1),
559 dimnames=c(dimnames(tab),
560 list(NULL)))
561 }
562 rn <- rownames(tab)
563 ii <- (grepl("(unlab.val.)",rn,fixed=TRUE) | grepl("(unlab.mss.)",rn,fixed=TRUE) |
564 grepl("NA M ",rn,fixed=TRUE))
565 ii <- ii & tab[,1,1] == 0
566 tab <- tab[!ii,,,drop=FALSE]
567 d <- dim(tab)
568 dn <- dimnames(tab)
569 tab[,-1,] <- apply(tab[,-1,,drop=FALSE],2:3,prc)
570 dim(tab) <- d
571 dimnames(tab) <- dn
572 attr(tab,"title") <- tab.title
573 }
574 descr <- stats$descr
575 if(length(descr)){
576 # if(length(dim(descr))!=2) browser()
577 cn.d <- colnames(descr)
578 descr <- t(t(descr[-1,,drop=FALSE])/descr[1,]) # From sums to (weighted) means ...
579 descr[2,] <- sqrt(descr[2,] - descr[1,]^2)
580
581 rnge <- stats$range
582 if(ncol(descr)==2){
583 if(unweighted)
584 descr <- rbind(cbind(rnge,rnge),descr)
585 else{
586 descr <- as.matrix(c(rnge,descr[,2]))
587 cn.d <- cn.d[2]
588 }
589 }
590 else
591 descr <- as.matrix(c(rnge,descr))
592 rownames(descr) <- c("Min","Max","Mean","Std.Dev.")
593 colnames(descr) <- cn.d
594 }
595 cbe@stats <- list(tab=tab,descr=descr)
596 cbe
597 }
598
599 fixupcodebookEntryDatetime <- function(cbe){
600
601 miss <- cbe@stats$missings[1]
602 NAs <- cbe@stats$missings[2]
603 Min <- cbe@stats$range[1]
604 Max <- cbe@stats$range[2]
605
606 origin <- unname(cbe@spec["Origin:"])
607
608 descr <- c(
609 Min=format(as.POSIXct(Min,origin=origin)),
610 Max=format(as.POSIXct(Max,origin=origin))
611 )
612 descr[] <- format(descr[])
613 descr <- as.matrix(descr)
614
615 cbe@stats <- list(descr=descr)
616 cbe
617 }
618
619 setMethod("head",signature(x="importer"),
620 function(x,n=20,...){
621 y <- utils::head.matrix(x,n=n,...)
622 rownames(y) <- 1:n
623 return(y)
624 })
625 setMethod("tail",signature(x="importer"),
626 function(x,n=20,...){
627 y <- utils::tail.matrix(x,n=n,...)
628 rownames(y) <- seq.int(to=nrow(x),length.out=n)
629 return(y)
630 })
631
632 as.data.frame.importer <- function(x, row.names = NULL, optional = FALSE, ...){
633 stop("\"importer\" objects cannot be coerced into data frames directly.
634 First apply 'as.data.set()' or 'subset()'.")
635 }
636
637 as.data.frame.spss.system.importer <- as.data.frame.importer
638 as.data.frame.spss.portable.importer <- as.data.frame.importer
639 as.data.frame.spss.fixed.importer <- as.data.frame.importer
640 as.data.frame.Stata.importer <- as.data.frame.importer
641 as.data.frame.Stata_new.importer <- as.data.frame.importer