Debian Codegraph @

R/percent.R

raw
1 percent <- function(x,...) UseMethod("percent")
2
3 percent.default <- function(x,weights=NULL,total=!(se || ci),
4 se=FALSE,ci=FALSE,ci.level=.95,
5 total.name="N",perc.label="Percentage",...){
6 subst <- substitute(x)
7 x.label <- paste(deparse(subst))
8 tab <- Table(x,weights=weights,total=FALSE,...)
9 tabsum <- sum(tab)
10 perc <- drop(100*tab/tabsum)
11 #names(perc) <- rownames(tab)
12
13 if(total.name %in% names(perc)) total.name <- paste("_",total.name,"_",sep="")
14
15 if(!se && !ci){
16 if(total)
17 perc <- c(perc,structure(tabsum,names=total.name))
18 perc <- as.matrix(perc)
19 colnames(perc) <- x.label
20 drop(perc)
21 }
22 else {
23 perc <- t(as.matrix(perc))
24 rownames(perc) <- perc.label
25 prop <- tab/tabsum
26 var.prop <- prop*(1-prop)/tabsum
27 se.perc <- 100*sqrt(var.prop)
28 if(se){
29 perc <- rbind(perc,se=se.perc)
30 }
31 if(ci){
32 alpha <- (1-ci.level)/2
33 lower <- upper <- numeric(length(tab))
34 isnull <- tab == 0
35 isfull <- tab == tabsum
36 lower[!isnull] <- qbeta(alpha,tab[!isnull],tabsum-tab[!isnull]+1)
37 lower[isnull] <- 0
38 upper[!isfull] <- qbeta(1-alpha,tab[!isfull]+1,tabsum-tab[!isfull])
39 upper[isfull] <- 1
40 #lower <- qnorm(alpha,mean=prop,sd=sqrt(var.prop))
41 #upper <- qnorm(1-alpha,mean=prop,sd=sqrt(var.prop))
42 perc <- rbind(perc,lower=100*lower,upper=100*upper)
43 }
44 if(total){
45 total <- numeric(nrow(perc))
46 total[] <- tabsum
47 total <- t(as.matrix(total))
48 rownames(total) <- total.name
49 perc <- cbind(perc,t(total))
50 }
51 names(dimnames(perc))[2] <- x.label
52 names(dimnames(perc))[is.na(names(dimnames(perc)))] <- ""
53 drop(perc)
54 }
55 }
56
57 percent.logical <- function(x,weights=NULL,total=!(se || ci),
58 se=FALSE,ci=FALSE,ci.level=.95,
59 total.name="N",perc.label="Percentage",...){
60 subst <- substitute(x)
61 x.label <- paste(deparse(subst))
62 tab <- drop(Table(x,weights=weights,total=FALSE,...))
63 N <- sum(tab)
64 n <- tab["TRUE"]
65 p <- n/N
66 perc <- structure(c(100*p),names=perc.label)
67 if(se){
68 var <- p*(1-p)/N
69 perc <- c(perc,se=100*sqrt(var))
70 }
71 if(ci){
72 if(is.finite(p)){
73 alpha <- (1-ci.level)/2
74 lower <- if(p) qbeta(alpha,n,N-n+1) else 0
75 upper <- if(p<1) qbeta(1-alpha,n+1,N-n) else 1
76 perc <- c(perc,lower=100*lower,upper=100*upper)
77 }
78 else
79 perc <- c(perc,lower=NA,upper=NA)
80 }
81 if(total){
82 perc <- c(perc,structure(N,names=total.name))
83 }
84 perc <- as.matrix(perc)
85 colnames(perc) <- x.label
86 drop(perc)
87 }
88