【发布时间】:2017-07-25 01:37:29
【问题描述】:
我有一个看起来像这样的函数:
organize.table <- function(x,y = NULL, col = NULL, row = NULL, sort = NULL, sort.row = sort,
sort.col = sort, total = TRUE, other = TRUE, ...){
if((!is.factor(x) & !is.character(x)) | (!is.factor(y) & !is.character(y))){
stop("Either x or y is not a factor", call. = FALSE)
}
if(length(x) != length(y)){
stop("Length of x not equal to y", call. = FALSE)
}
if(!(sort.row %in% c('desc', 'asc')) | is.null(sort.row) |
!(sort.col %in% c('desc', 'asc')) | is.null(sort.col)){
stop("sort.row or sort.col not equal to NULL, 'desc', or 'asc'")
}
if((!is.null(sort.row) | !is.null(sort.col)) & total == FALSE){
stop("To use sort.row or sort.col, parameter 'total' must equal TRUE", call. = FALSE)
}
if(length(unique(y)) <= col | length(unique(x)) <= row){
stop("Error: Dimension mismatch between x and col or y and row. col < the unique number of
attributes in y or row < the unique number of attributes in x", call. = FALSE)
}
tabs <- table(x,y, ...)
cs <- ncol(tabs)
rs <- nrow(tabs)
if(total == TRUE){
tabs <- cbind(tabs, rowSums(tabs))
colname.tabs <- c(colnames(tabs)[1:cs], 'Total')
colnames(tabs) <- colname.tabs
tabs <- rbind(tabs, colSums(tabs))
rowname.tabs <- c(rownames(tabs)[1:rs], 'Total')
rownames(tabs) <- rowname.tabs
}
if(sort.row == 'desc') {
tabs <- tabs[order(-tabs$Total), ]
tabs <- tabs[rowname.tabs,]
}
if(sort.row == 'asc') {
tabs <- tabs[order( tabs$Total), ]
tabs <- rowname.tabs
}
if(sort.col == 'desc') {
tabs <- tabs[ ,order(-tabs['Total', ])]
tabs <- colname.tabs
}
if(sort.col == 'asc') {
tabs <- tabs[ ,order( tabs['Total', ])]
tabs <- colname.tabs
}
if(other == TRUE){
ra <- row + 1; ca <- col + 1
tabs <- cbind(tabs[ ,1:col], rowSums(tabs[ ,ca:cs]), tabs$Total)
tabs <- rbind(tabs[1:row, ], colSums(tabs[ra:rs, ]), tabs['Total',])
rownames(tabs) <- c(rownames(tabs)[1:row], 'Other', 'Total')
colnames(tabs) <- c(colnames(tabs)[1:col], 'Other', 'Total')
}
}
在工作时,我经常需要生成一个双向表,该表需要该表中的顶部 ncol 和 nrow 值,并将表的其余部分总结为 其他。另外,我通常需要一个 Total 列和行。有时我需要最少(最少)的 ncol 和 nrow 值。这实际上是一个灵活的表函数。我收到错误,即:
tabs$Total 中的错误:$ 运算符对原子向量无效。
有关解决此问题的任何建议或代码?
【问题讨论】:
标签: r