不幸的是,似乎还没有 R 包可以生成像 SPSS 这样的好输出。大多数用于生成表格的函数似乎都定义了自己的特殊格式,如果您想以其他方式导出或处理表格,这会给您带来麻烦。
但我确信 R 能够做到这一点,所以我开始编写自己的函数。我很高兴与您分享结果(工作正在进行中,但已完成工作):
以下函数为 data.frame 中的所有因子变量返回因子变量“变量”的每个级别的频率或百分比 (calc="perc")。
最重要的可能是输出是一个简单且用户友好的 data.frame。因此,与许多其他功能相比,以任何您想要的方式导出结果并使用它都没有问题。
我意识到进一步改进的潜力很大,即增加了选择行与列百分比计算的可能性等。
contitable <- function( survey_data, variable, calc="freq" ){
# Check which variables are not given as factor
# and exlude them from the given data.frame
survey_data_factor_test <- as.logical( sapply( Survey, FUN=is.factor) )
survey_data <- subset( survey_data, select=which( survey_data_factor_test ) )
# Inform the user about deleted variables
# is that proper use of printing to console during a function call??
# for now it worksjust fine...
flush.console()
writeLines( paste( "\n ", sum( !survey_data_factor_test, na.rm=TRUE),
"non-factor variable(s) were excluded\n" ) )
variable_levels <- levels(survey_data[ , variable ])
variable_levels_length <- length( variable_levels )
# Initializing the data.frame which will gather the results
result <- data.frame( "Variable", "Levels", t(rep( 1, each=variable_levels_length ) ) )
result_column_names <- paste( variable, variable_levels, sep="." )
names(result) <- c("Variable", "Levels", result_column_names )
for(column in 1:length( names(survey_data) ) ){
column_levels_length <- length( levels( survey_data[ , column ] ) )
result_block <- as.data.frame( rep( names(survey_data)[column], each=column_levels_length ) )
result_block <- cbind( result_block, as.data.frame( levels( survey_data[,column] ) ) )
names(result_block) <- c( "Variable", "Levels" )
results <- table( survey_data[ , column ], survey_data[ , variable ] )
if( calc=="perc" ){
results <- apply( results, MARGIN=2, FUN=function(x){ x/sum(x) })
results <- round( results*100, 1 )
}
results <- unclass(results)
results <- as.data.frame( results )
names( results ) <- result_column_names
rownames(results) <- NULL
result_block <- cbind( result_block, results)
result <- rbind( result, result_block )
}
result <- result[-1,]
return( result )
}