Debian Codegraph @

R/codebook-methods.R

raw
1 setMethod("codebook","data.set",function(x,weights,unweighted=TRUE,...){
2 weights <- eval(substitute(weights),x,parent.frame())
3 cb <- lapply(x,codebookEntry,weights=weights,unweighted=unweighted)
4 new("codebook",cb)
5 })
6
7 setMethod("codebook","item",function(x,weights,unweighted=TRUE,...){
8 xname <- paste(deparse(substitute(x)))
9 cb <- list(codebookEntry(x,weights=weights,unweighted=unweighted))
10 names(cb) <- xname
11 new("codebook",cb)
12 })
13
14 setMethod("codebook","data.frame",function(x,weights,unweighted=TRUE,...){
15 weights <- eval(substitute(weights),x,parent.frame())
16 cb <- lapply(x,codebookEntry,weights=weights,unweighted=unweighted)
17 new("codebook",cb)
18 })
19
20 setMethod("codebook","tbl_df",function(x,weights,unweighted=TRUE,...){
21 weights <- eval(substitute(weights),x,parent.frame())
22 cb <- lapply(x,codebookEntry,weights=weights,unweighted=unweighted)
23 new("codebook",cb)
24 })
25
26 setMethod("codebook","atomic",function(x,weights,unweighted=TRUE,...){
27 xname <- paste(deparse(substitute(x)))
28 cb <- list(codebookEntry(x,weights=weights,unweighted=unweighted))
29 names(cb) <- xname
30 new("codebook",cb)
31 })
32
33 setMethod("codebook","factor",function(x,weights,unweighted=TRUE,...){
34 xname <- paste(deparse(substitute(x)))
35 cb <- list(codebookEntry(x,weights=weights,unweighted=unweighted))
36 names(cb) <- xname
37 new("codebook",cb)
38 })
39
40 setMethod("codebook","ANY",function(x,weights,unweighted=TRUE,...){
41 xname <- paste(deparse(substitute(x)))
42 cb <- list(codebookEntry(x,weights=weights,unweighted=unweighted))
43 names(cb) <- xname
44 new("codebook",cb)
45 })
46
47 setMethod("codebook","NULL",function(x,weights,unweighted=TRUE,...)NULL)
48
49 setMethod("codebookEntry","item",function(x,weights,unweighted=TRUE,...){
50 annotation <- annotation(x)
51 filter <- [email protected]
52 spec <- c(
53 "Storage mode:"=storage.mode(x),
54 "Measurement:"=measurement(x)
55 )
56 if(length(filter)) spec <- c(spec,
57 switch(class(filter),
58 missing.values = c("Missing values:" = format(filter)),
59 valid.values = c("Valid values:" = format(filter)),
60 valid.range = c("Valid range:" = format(filter))
61 ))
62 stats <- switch(measurement(x),
63 nominal=,ordinal=codebookStatsCateg(x,weights=weights,unweighted=unweighted),
64 interval=,ratio=codebookStatsMetric(x,weights=weights,unweighted=unweighted)
65 )
66 cbe <- new("codebookEntry",
67 spec = spec,
68 stats = stats,
69 annotation = annotation
70 )
71 return(cbe)
72 })
73
74 NAtab <- function(isna,weights=NULL){
75 if(!length(weights))
76 weights <- rep(1,length(isna))
77 counts <- c(
78 Valid = sum(weights*!isna),
79 "Missing (NA)" = sum(weights*isna),
80 Total = sum(weights)
81 )
82 perc <- 100*counts/counts[3]
83 perc[3] <- NA
84 cbind(N=counts,
85 Percent=perc)
86 }
87
88
89 setMethod("codebookEntry","ANY",function(x,weights,unweighted=TRUE,...){
90
91 if(length(attr(x,"label")))
92 annotation <- c(description=attr(x,"label"))
93 else
94 annotation <- NULL
95
96 spec <- c("Storage mode:"=storage.mode(x))
97
98 isat <- is.atomic(x)
99 if(isat)
100 isna <- is.na(x)
101 else
102 isna <- FALSE
103
104 if(mode(x) == "numeric"){
105 descr <- Descriptives(x)
106 if(length(descr) > 4)
107 descr <- descr[1:4]
108 if(length(weights) && length(descr) > 2){ # There is more than a range
109 wdescr <- Descriptives(x,weights)
110 if(unweighted)
111 descr <- collect(Unweighted=format(descr),
112 Weighted=format(wdescr))
113 else
114 descr <- as.matrix(format(wdescr))
115 }
116 else
117 descr <- as.matrix(format(descr))
118 }
119 else
120 descr <- NULL
121
122 if(any(isna)){
123 tab <- NAtab(isna)
124 if(length(weights)){
125 wtab <- NAtab(isna,weights)
126 if(unweighted)
127 tab <- collect(Unweighted=tab,
128 Weighted=wtab)
129 else
130 tab <- array(wtab,
131 dim=c(dim(tab),1),
132 dimnames=c(dimnames(tab),
133 list(NULL)))
134 }
135 else
136 tab <- array(tab,
137 dim=c(dim(tab),1),
138 dimnames=c(dimnames(tab),
139 list(NULL)))
140 attr(tab,"title") <- "Valid and missing values"
141 } else
142 tab <- integer(0)
143
144 stats <- list(tab=tab,
145 descr=descr)
146
147 new("codebookEntry",
148 spec = spec,
149 stats = stats,
150 annotation = annotation
151 )
152 })
153
154 rwnexp <- function(mat,nms){
155 res <- array(0,c(length(nms),ncol(mat)),
156 dimnames=list(nms,colnames(mat)))
157 rn <- rownames(mat)
158 res[rn,] <- mat
159 return(res)
160 }
161
162 codebookTable_factor <- function(x,weights=NULL,...){
163
164 if(!length(weights))
165 weights <- rep(1,length(x))
166
167 isna <- is.na(x)
168 counts <- rowsum(weights[!isna],x[!isna])
169 lev <- levels(x)
170 counts <- rwnexp(counts,lev)
171
172 NAs <- sum(weights*isna)
173
174 tab <- cbind(counts,100*counts/sum(counts))
175 if(any(isna)) {
176 labs <- sQuote(levels(x))
177 if(nlevels(x))
178 labs <- paste(format(c(1:nlevels(x),NA),justify="right"),
179 format(c(labs,""),justify="left")
180 )
181 else
182 labs <- "NA"
183 tab <- rbind(tab,c(NAs,NA))
184 counts <- c(counts,NAs)
185 tab <- cbind(tab,100*counts/sum(counts))
186 colnames(tab) <- c("N","Valid","Total")
187 }
188 else {
189 labs <- sQuote(levels(x))
190 labs <- paste(format(1:nlevels(x),justify="right"),
191 format(labs,justify="left")
192 )
193 colnames(tab) <- c("N","Valid")
194 }
195 rownames(tab) <- labs
196
197
198 return(tab)
199 }
200
201 setMethod("codebookEntry","factor",function(x,weights=NULL,unweighted=TRUE,...){
202
203 tab <- codebookTable_factor(x)
204 if(length(weights)){
205 wtab <- codebookTable_factor(x,weights=weights)
206 if(unweighted)
207 tab <- collect(Unweighted=tab,
208 Weighted=wtab)
209 else {
210 tab <- wtab
211 tab.dn <- dimnames(tab)
212 tab.d <- dim(tab)
213 dim(tab) <- c(tab.d,1)
214 dimnames(tab) <- c(tab.dn,list(NULL))
215 }
216 }
217 else{
218 tab.dn <- dimnames(tab)
219 tab.d <- dim(tab)
220 dim(tab) <- c(tab.d,1)
221 dimnames(tab) <- c(tab.dn,list(NULL))
222 }
223 attr(tab,"title") <- "Levels and labels"
224
225 if(length(attr(x,"label")))
226 annotation <- c(description=attr(x,"label"))
227 else
228 annotation <- NULL
229
230 spec <- c("Storage mode:"=storage.mode(x))
231 spec <- if(is.ordered(x)) c(spec,
232 "Ordered factor with"=paste(nlevels(x),"levels"))
233 else c(spec,
234 "Factor with"=paste(nlevels(x),"levels"))
235
236 stats <- list(tab=tab)
237 new("codebookEntry",
238 spec = spec,
239 stats = stats,
240 annotation = annotation
241 )
242 })
243
244 setMethod("codebookEntry","character",function(x,weights=NULL,unweighted=TRUE,...){
245 spec <- c("Storage mode:"=storage.mode(x))
246 isna <- is.na(x)
247 descr <- codebookStatsChar(x)
248 descr <- descr$descr
249
250 if(any(isna)){
251 tab <- NAtab(isna)
252 if(length(weights)){
253 wtab <- NAtab(isna,weights)
254 if(unweighted)
255 tab <- collect(Unweighted=tab,
256 Weighted=tab)
257 else
258 tab <- array(wtab,
259 dim=c(dim(tab),1),
260 dimnames=c(dimnames(tab),
261 list(NULL)))
262 }
263 else
264 tab <- array(tab,
265 dim=c(dim(tab),1),
266 dimnames=c(dimnames(tab),
267 list(NULL)))
268 attr(tab,"title") <- "Valid and missing values"
269 } else
270 tab <- integer(0)
271
272 stats <- list(tab=tab,
273 descr=descr)
274
275 new("codebookEntry",
276 spec = spec,
277 stats = stats,
278 annotation = NULL
279 )
280 })
281
282 codebookTable_logical <- function(x,weights=NULL,...){
283
284 if(!length(weights))
285 weights <- rep(1,length(x))
286
287 isna <- is.na(x)
288 counts <- rowsum(weights[!isna],x[!isna])
289 NAs <- sum(weights*isna)
290
291 tab <- cbind(counts,100*counts/sum(counts))
292 if(any(isna)) {
293 labs <- c("FALSE","TRUE","NA")
294 tab <- rbind(tab,c(NAs,NA))
295 counts <- c(counts,NAs)
296 tab <- cbind(tab,100*counts/sum(counts))
297 colnames(tab) <- c("N","Valid","Total")
298 }
299 else {
300 labs <- c("FALSE","TRUE")
301 colnames(tab) <- c("N","Valid")
302 }
303 rownames(tab) <- labs
304
305
306 return(tab)
307 }
308
309 setMethod("codebookEntry","logical",function(x,weights=NULL,unweighted=TRUE,...){
310
311 tab <- codebookTable_logical(x)
312 if(length(weights)){
313 wtab <- codebookTable_logical(x,weights=weights)
314 if(unweighted)
315 tab <- collect(Unweighted=tab,
316 Weighted=wtab)
317 else {
318 tab <- wtab
319 tab.dn <- dimnames(tab)
320 tab.d <- dim(tab)
321 dim(tab) <- c(tab.d,1)
322 dimnames(tab) <- c(tab.dn,list(NULL))
323 }
324 }
325 else{
326 tab.dn <- dimnames(tab)
327 tab.d <- dim(tab)
328 dim(tab) <- c(tab.d,1)
329 dimnames(tab) <- c(tab.dn,list(NULL))
330 }
331 attr(tab,"title") <- "Logical values"
332
333 if(length(attr(x,"label")))
334 annotation <- c(description=attr(x,"label"))
335 else
336 annotation <- NULL
337
338 spec <- c("Storage mode:"=storage.mode(x))
339
340 stats <- list(tab=tab)
341 new("codebookEntry",
342 spec = spec,
343 stats = stats,
344 annotation = annotation
345 )
346 })
347
348
349 codebookStatsCateg <- function(x,weights=NULL,unweighted=TRUE,...){
350 vl <- labels(x)
351 ic <- inherits(x,"character")
352 if(length(vl) || !ic){
353 tab <- codebookTable_item(x)
354 tab.title <- attr(tab,"title")
355 if(length(weights)){
356 wtab <- codebookTable_item(x,weights)
357 if(unweighted)
358 tab <- collect(Unweighted=tab,
359 Weighted=wtab)
360 else
361 tab <- array(wtab,
362 dim=c(dim(tab),1),
363 dimnames=c(dimnames(tab),
364 list(NULL)))
365 }
366 else
367 tab <- array(tab,
368 dim=c(dim(tab),1),
369 dimnames=c(dimnames(tab),
370 list(NULL)))
371 attr(tab,"title") <- tab.title
372 list(tab=tab)
373 }
374 else
375 codebookStatsChar(x)
376 }
377
378 codebookStatsChar <- function(x,...){
379 descr <- structure(dQuote(range(x,na.rm=TRUE)),
380 names=c("Min","Max"))
381 descr <- as.matrix(descr)
382 list(
383 tab = NULL,
384 descr = descr
385 )
386 }
387
388 codebookStatsMetric <- function(x,weights=TRUE,unweighted=TRUE,...){
389
390 tab <- codebookTable_item(x,drop.unlabelled=TRUE)
391 tab.title <- attr(tab,"title")
392 if(length(weights) && length(tab)){
393 wtab <- codebookTable_item(x,weights=weights,
394 drop.unlabelled=TRUE)
395 if(unweighted)
396 tab <- collect(Unweighted=tab,
397 Weighted=wtab)
398 else
399 tab <- array(wtab,
400 dim=c(dim(tab),1),
401 dimnames=c(dimnames(tab),
402 list(NULL)))
403 attr(tab,"title") <- tab.title
404 }
405 else if(length(tab)){
406 tab <- array(tab,
407 dim=c(dim(tab),1),
408 dimnames=c(dimnames(tab),
409 list(NULL)))
410 attr(tab,"title") <- tab.title
411 }
412
413 descr <- Descriptives(x)[1:4]
414 if(length(weights)){
415 wdescr <- Descriptives(x,weights)[1:4]
416 if(unweighted)
417 descr <- collect(Unweighted=descr,
418 Weighted=wdescr)
419 else
420 descr <- as.matrix(wdescr)
421 }
422 else
423 descr <- as.matrix(descr)
424 list(
425 tab=tab,
426 descr=descr
427 )
428 }
429
430 codebookTable_item <- function(x,weights=NULL,drop.unlabelled=FALSE,drop.empty=TRUE){
431
432 is.m <- is.missing(x)
433 isNA <- is.na(x)
434 vl <- labels(x)
435 if(!length(weights)){
436 weights <- rep(1,length(x))
437 }
438 if(length(vl)){
439 vvl <- vl@values
440 lvl <- [email protected]
441 valid <- !is.missing2(vvl,[email protected])
442 i <- match([email protected],vvl,nomatch=0L)
443 tab <- drop(rowsum(weights,i))
444 if("0" %in% names(tab)){
445 ii <- match("0",names(tab))
446 tab <- tab[-ii]
447 }
448 if(length(tab) < length(vvl)){
449 tab0 <- numeric(length(vvl))
450 ii <- as.integer(names(tab))
451 tab0[ii] <- tab
452 tab <- tab0
453 }
454 names(tab) <- as.character(vvl)
455 lab <- sQuote([email protected])
456 tab.title <- "Values and labels"
457 }
458 else {
459 valid <- logical(0)
460 tab <- c()
461 lab <- c()
462 i <- logical(length(x))
463 tab.title <- "Values"
464 }
465
466 ovld <- sum(weights*(!is.m & !i))
467 omiss <- sum(weights*(is.m & !i & !isNA))
468 NAs <- sum(weights*(isNA))
469
470 if(ovld | !drop.empty){
471 tab <- c(tab," "=ovld)
472 lab <- c(lab,"(unlab.val.)")
473 valid <- c(valid,TRUE)
474 }
475
476 if(omiss | !drop.empty){
477 tab <- c(tab," "=omiss)
478 lab <- c(lab,"(unlab.mss.)")
479 valid <- c(valid,FALSE)
480 }
481 if(NAs | !drop.empty){
482 tab <- c(tab,"NA"=NAs)
483 lab <- c(lab,"")
484 valid <- c(valid,FALSE)
485 }
486
487 if(any(!valid)){
488 missing.marker <- "M"
489 valid.marker <- paste(rep(" ",nchar(missing.marker)),collapse="")
490 lab <- paste(ifelse(valid,valid.marker,missing.marker),lab)
491 }
492 tab.nonzero <- tab>0
493 tab.keep <- tab.nonzero | !drop.empty
494 tab <- tab[valid | tab.keep]
495 lab <- lab[valid | tab.keep]
496 valid <- valid[valid | tab.keep]
497 if(any(!valid)){
498 vperc <- rep(NA,length(tab))
499 vtab <- tab[valid]
500 Nvalid <- sum(vtab)
501 if(Nvalid) vperc[valid] <- 100 * vtab/Nvalid
502 else vperc[valid] <- 0
503 tperc <- 100 * tab/sum(tab)
504 tab <- cbind(N=tab,Valid=vperc,Total=tperc)
505 } else {
506 tperc <- 100 * tab/sum(tab)
507 tab <- cbind(N=tab,Percent=tperc)
508 }
509 rownames(tab) <- names(tperc)
510 if(drop.unlabelled){
511 drp <- match("(unlab.val.)",trimws(lab),nomatch=0L)
512 if(drp > 0){
513 tab <- tab[-drp,,drop=FALSE]
514 lab <- lab[-drp]
515
516 }
517 if(all(is.na(tab[,2])) && length(tab)){
518 tab <- tab[,-2,drop=FALSE]
519 colnames(tab) <- c("N","Percent")
520 }
521 }
522 if(!length(tab))
523 tab <- NULL
524 else {
525 rownames(tab) <- paste(format(rownames(tab),justify="right"),format(lab,justify="left"))
526 attr(tab,"title") <- tab.title
527 }
528 return(tab)
529 }
530
531
532 setMethod("as.character","codebook",function(x,...){
533 width <- getOption("width")
534 toprule <- paste(rep("=",width),collapse="")
535 midrule <- paste(rep("-",width),collapse="")
536 out <- mapply(format,[email protected],name=names(x),toprule=toprule,midrule=midrule)
537 unlist(out)
538 })
539
540 setMethod("show","codebook",function(object){
541 width <- getOption("width")
542 toprule <- paste(rep("=",width),collapse="")
543 midrule <- paste(rep("-",width),collapse="")
544 out <- mapply(format,[email protected],name=names(object),toprule=toprule,midrule=midrule)
545 out <- unlist(out)
546 writeLines(out)
547 })
548
549
550 Write.codebook <- function(x,file=stdout(),...){
551 width <- getOption("width")
552 toprule <- paste(rep("=",width),collapse="")
553 midrule <- paste(rep("-",width),collapse="")
554 out <- mapply(format,[email protected],name=names(x),toprule=toprule,midrule=midrule)
555 out <- unlist(out)
556 writeLines(out,con=file)
557 }
558
559
560 format.codebookEntry <- function(x,name="",width=getOption("width"),
561 toprule=paste(rep("=",width),collapse=""),
562 midrule=paste(rep("-",width),collapse=""),
563 ...
564 ){
565
566 annot <- x@annotation
567 description <- annot["description"]
568 wording <- annot["wording"]
569 if(length(annot)) annot <- annot[names(annot) %nin% c("description","wording")]
570
571 title <- strwrap(if(length(description) && !is.na(description))
572 paste(name[1],sQuote(description))
573 else name[1] ,width=width,prefix=" ")
574
575 wording <- if(length(wording) && !is.na(wording))
576 strwrap(dQuote(wording),width=width,prefix=" ")
577 else NULL
578
579 spec <- paste(" ",names(x@spec),x@spec)
580 tab <- unclass(x@stats$tab)
581 descr <- unclass(x@stats$descr)
582
583 if(length(tab)){
584
585 tab.title <- attr(tab,"title")
586 tab.d <- dim(tab)
587 tab.dn <- dimnames(tab)
588 tab <- apply(tab,3,format_cb_table)
589 #tab <- lapply(tab,unlist)
590 #tab <- do.call(cbind,tab)
591 rn <- rownames(tab)
592 rn[1] <- tab.title
593 rn <- format(rn)
594 if(tab.d[3]>1){
595 tab <- cbind(" "=rn,tab)
596 tab <- rbind(colnames(tab),"",tab)
597 tab <- apply(tab,2,format,justify="right")
598 }
599 else {
600 tab <- cbind(rn,tab)
601 }
602 tab <- paste(" ",apply(tab,1,paste,collapse=" "))
603 }
604 if(!is.matrix(descr)) descr <- NULL
605 if(length(descr)){
606 descr.rn <- format(paste(rownames(descr),":",sep=""),justify="right")
607 if(is.numeric(descr[]))
608 descr[] <- formatC(descr[],format="f",digits=3)
609 descr[] <- gsub("NA","",descr[])
610 if(!length(ncol(descr))) browser()
611 if(ncol(descr) > 1){
612 descr.rn <- c("","",descr.rn)
613 descr <- rbind(colnames(descr),"",descr)
614 }
615 descr <- cbind(descr.rn,descr)
616 descr <- apply(descr,2,format,justify="right")
617 descr <- paste(" ",apply(descr,1,paste,collapse=" "))
618 }
619 if(length(tab) && length(descr)){
620 statstab <- format(c(tab,"",descr),justify="left")
621 }
622 else if(length(tab)){
623 statstab <- tab
624 }
625 else if(length(descr)){
626 statstab <- descr
627 }
628 else
629 statstab <- NULL
630
631 annot.out <- character()
632 if(length(annot)){
633 for(i in seq_len(length(annot))){
634 annot.i <- annot[i]
635 nm.i <- trimws(names(annot.i))
636 annot.i <- strwrap(annot.i,width=getOption("width")-8-4)
637 annot.i <- c(paste(" ",annot.i),"")
638 if(nzchar(nm.i)){
639 annot.i <- c(
640 paste(" ",nm.i,":",sep=""),
641 annot.i
642 )
643 }
644 annot.out <- c(annot.out,annot.i)
645 }
646 }
647 c(
648 toprule,
649 "",
650 title,
651 if(length(wording)) c(
652 "",
653 wording
654 ),
655 "",
656 midrule,
657 "",
658 spec,
659 "",
660 statstab,
661 "",
662 if(length(annot.out)) annot.out
663 )
664 }
665
666 #setMethod("format","codebookEntry",format.codebookEntry)
667
668
669 format_cb_table <- function(tab){
670 cn <- colnames(tab)
671 if(ncol(tab)>2){
672 if(all(trunc(tab[,1])==tab[,1])){
673 tab <- cbind(
674 formatC(tab[,1,drop=FALSE],format="d"),
675 formatC(tab[,2],format="f",digits=1),
676 formatC(tab[,3],format="f",digits=1)
677 )
678 } else {
679 tab <- cbind(
680 formatC(tab[,1,drop=FALSE],format="f",digits=1),
681 formatC(tab[,2],format="f",digits=1),
682 formatC(tab[,3],format="f",digits=1)
683 )
684 }
685 }
686 else {
687 if(all(trunc(tab[,1])==tab[,1])){
688 tab <- cbind(
689 formatC(tab[,1,drop=FALSE],format="d"),
690 formatC(tab[,2],format="f",digits=1)
691 )
692 } else {
693 tab <- cbind(
694 formatC(tab[,1,drop=FALSE],format="f",digits=1),
695 formatC(tab[,2],format="f",digits=1)
696 )
697 }
698
699 }
700 tab[tab=="NA"] <- ""
701 tab <- rbind(" "=cn,"",tab)
702 tab <- format(tab,justify="right")
703 tab <- apply(tab,1,paste,collapse=" ")
704 tab
705 }
706
707 setMethod("[",signature(x="codebook",i="atomic",j="missing",drop="ANY"),
708 function(x,i,j,...,drop=TRUE){
709 if(is.character(i))
710 i <- match(i,names(x))
711 cb <- [email protected][i]
712 if(!length(cb)) return(NULL)
713 if(is.numeric(i) || is.logical(i))
714 names(cb) <- names(x)[i]
715 else return(NULL)
716 new("codebook",cb)
717 })
718
719 setMethod("$",signature(x="codebook"),
720 function(x,name){
721 i <- match(name,names(x))
722 cb <- [email protected][i]
723 if(!length(cb)) return(NULL)
724 names(cb) <- name
725 new("codebook",cb)
726 })
727
728 setMethod("[[",signature(x="codebook"),
729 function(x,i,...){
730 if(is.character(i))
731 i <- match(i,names(x))
732 cb <- [email protected][i]
733 if(!length(cb)) return(NULL)
734 if(is.numeric(i) || is.logical(i))
735 names(cb) <- names(x)[i]
736 new("codebook",cb)
737 })