I also had problems many times with an unusable output R ... The only solution I found was to write my own function and I am happy to share it with you here:
The following function returns for all factor variables in data.frame the frequency or percentage (calc = "perc") for each level of the variable variable "variable".
Most importantly, the output is a simple user-friendly data.frame. Thus, there is no problem to export the results to work with it in any way.
I understand that there are many opportunities for further improvements, i.e. add the ability to select the calculation of the number of rows and columns, etc. This is a work in progress but is on a mission.
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 ) }
user3755360
source share