###分割表+パーセント
### xはtableの結果
### margins 1:横の%、2:縦の%、3:全体の%
### digitsは小数点以下の桁数
tab.prop <- function(x, margins=1, digits=2) {
xn <- ncol(x)
xm <- nrow(x)
if(margins == 1) {
x1<-round(prop.table(x,1)*100,digits=digits)
} else if(margins == 2) {
x1<-round(prop.table(x,2)*100,digits=digits)
} else {
x1<-round(prop.table(x)*100,digits=digits)
}
x0<-addmargins(x,c(1,2))
x1<-addmargins(x1,c(1,2))
xn2<-(xn+1)*2
xx<-data.frame(matrix(0,xm+1,xn2));
# xx<-as.table(matrix(0,xm+1,xn2));
rownames(xx)=rownames(x0);rownames(xx)[xm+1]<-"Total"
cc<-colnames(x0)
for(i in 0:xn+1){
xx[,i*2-1]<-x0[,i];
xx[,i*2]<-x1[,i]
colnames(xx)[i*2-1]<-cc[i]
colnames(xx)[i*2]<-"%"
}
colnames(xx)[((xn+1)*2-1)]<-"Total"
if(margins == 1) {
a<-round(x1[xm+1,]/x1[xm+1,xn+1]*100,digits=digits)
for(i in 0:xn+1){
xx[xm+1,i*2]<-a[i]
}
} else if(margins == 2) {
a<-round(x1[,xn+1]/x1[xm+1,xn+1]*100,digits=digits)
xx[,(xn+1)*2]<-a
}
return(xx)
}