これが私の解決策です。かわいくないので、頭に鞄をかぶせます(関数で包みます)。また、それが一般的であることを示すために別の変数を追加します(私は願っています)。
prettyTable <- function(x) {
tbl <- apply(x, 2, function(m) {
marc <- sort(unique(m))
cnt <- matrix(table(m), ncol = 1)
out <- cbind(marc, cnt)
out <- out[order(marc), ] # do sorting
out <- cbind(out, round(prop.table(out, 2)[, 2] * 100, 2))
})
x2 <- do.call("rbind", tbl)
spaces <- unlist(lapply(apply(x, 2, unique), length))
space.names <- names(spaces)
spc <- rep("", sum(spaces))
ind <- cumsum(spaces)
ind <- abs(spaces - ind)+1
spc[ind] <- space.names
out <- cbind(spc, x2)
out <- as.data.frame(out)
names(out) <- c("Variable", "Levels", "Count", "Column N %")
out
}
prettyTable(x = mtcars[, c(2, 8:11)])
Variable Levels Count Column N %
1 cyl 4 11 34.38
2 6 7 21.88
3 8 14 43.75
4 vs 0 18 56.25
5 1 14 43.75
6 am 0 19 59.38
7 1 13 40.62
8 gear 3 15 46.88
9 4 12 37.5
10 5 5 15.62
11 carb 1 7 21.88
12 2 10 31.25
13 3 3 9.38
14 4 10 31.25
15 6 1 3.12
16 8 1 3.12
パッケージを使用googleVis
すると、便利なhtmlテーブルを作成できます。
plot(gvisTable(prettyTable(x = mtcars[, c(2, 8:11)])))
