第三种方式:
x <- read.table(text = "C1 C2 C3 C4
1 -1 -1 1
1 1 -1 1
1 1 -1 1
1 -1 1 -1 ", header = TRUE)
sapply(sapply(x, factor, levels = c(1, -1), simplify = FALSE), table)
C1 C2 C3 C4
1 4 2 1 3
-1 0 2 3 1
一些基准测试:
xx <- as.data.frame(matrix(sample(c(-1,1), 1e7, replace=TRUE), ncol=100))
Roland <- function(DF) {
res <- table(stack(DF))
res2 <- as.data.frame(res)
reshape(res2, timevar = "ind", idvar = "values", direction = "wide")
}
Roman <- function(x) {
sapply(sapply(x, factor, levels = c(1, -1), simplify = FALSE), table)
}
user20650 <- function(x) {
rbind(colSums(x == 1), colSums(x==-1))
}
require(microbenchmark)
microbenchmark(m1 <- Roland(xx), m2 <- Roman(xx), m3 <- user20650(xx), times = 2)
Unit: milliseconds
expr min lq median uq max neval
m1 <- Roland(xx) 17624.6297 17624.6297 18116.6595 18608.6893 18608.6893 2
m2 <- Roman(xx) 13838.2030 13838.2030 14301.9159 14765.6288 14765.6288 2
m3 <- user20650(xx) 786.3689 786.3689 788.7253 791.0818 791.0818 2