构建一个功能来自动化制表

时间:2017-03-09 21:03:29

标签: r loops

我正在尝试构建一个用于制表表构建的函数。从本质上讲,如果我有一堆分类变量,我希望能够将它们与计数和表格一起列表。百分比没有单独做每一个。我有大部分代码,但我有循环问题。基本上,我想要一个包含所有变量和表格的表格。相应的计数&百分比显示。我的循环是循环但只显示最终变量。见下面的代码。任何帮助,将不胜感激!

descriptives <- function(VARIABLEMATRIX){
for (i in 1:ncol(VARIABLEMATRIX)){
matper <- matrix(0, nrow=dim(table(VARIABLEMATRIX[ ,i])), ncol=1)
for (i in 1:dim(table(VARIABLEMATRIX[ ,i]))){
matper[i, ] <- paste(round(prop.table(table(VARIABLEMATRIX[ ,i]))[i]*100, 2), "%")
}

matcount <- matrix(0, nrow=dim(table(VARIABLEMATRIX[ ,i])), ncol=1)
for (i in 1:dim(table(VARIABLEMATRIX[ ,i]))){
matcount[i, ] <- table(VARIABLEMATRIX[ ,i])[i]
}

space <- matrix(c(colnames(VARIABLEMATRIX)[i], "", "", ""), ncol=4, nrow=1)
desc <- cbind("", names(table(VARIABLEMATRIX[ ,i])), matcount[ ,1], matper[ ,1])
desc <- rbind(space, desc)
return(desc)
}
}

播放数据集在这里:

ESRD <- rep(c("Y", "N"), each=10)
DIABETES <- rep(c("Y", "N", "Y", "N"), c(5, 5, 5, 5))
categoricalvariables <- cbind(ESRD, DIABETES)

我最终得到的是:

descriptives(categoricalvariables)
     [,1]       [,2] [,3] [,4]  
[1,] "DIABETES" ""   ""   ""    
[2,] ""         "N"  "10" "50 %"
[3,] ""         "Y"  "10" "50 %"

所需的输出将是:

descriptives(categoricalvariables)
[,1]       [,2] [,3] [,4]  
"ESRD"     ""   ""   "" 
""         "N"  "10" "50 %"
""         "Y"  "10" "50 %"
"DIABETES" ""   ""   ""    
""         "N"  "10" "50 %"
""         "Y"  "10" "50 %"

0 个答案:

没有答案