I have a dataset of about 100 variables and I would like to build a table with summaries of approximately 30 of these variables. To do this, I've manually run the table and other functions on these variables and rbinded the results. However, since I need to do this for 30+ vars, I would like to automate the process using a function.
Here is an example dataset:
df <- data.frame(v1=c('a','b','c','c','b'),v2=c('d','d','e','e','e'),cat=c('1low','1low','2med','3high','2med'))
The goal is to create a table like below (without the NAs).

Below is my code:
library(formattable)
# For var1 & var2, apply the table function and convert to dataframe so that the row labels are incorporated into dataset
var1.df <- as.data.frame(table(df$v1, df$cat))
# reshape to achive wide format (goal to view the count of each var1 level across low, med, high cats)
var1.df <- reshape(var1.df, idvar = "Var1", timevar = "Var2", direction = "wide")
# add col names
names(var1.df) <- c("vcat","low","med","high"); var1.df
# repeat above steps for next variable. in true dataset, I will need to repeat for 30 vars...
var2.df <- as.data.frame(table(df$v2, df$cat))
var2.df <- reshape(var2.df, idvar = "Var1", timevar = "Var2", direction = "wide")
names(var2.df) <- c("vcat","low","med","high")
# Create variable headings
var1.heading <- data.frame("variable 1",NA,NA,NA) # ideally, the NAs are blanks
names(var1.heading) <- c("vcat","low","med","high")
var2.heading <- data.frame("variable 2","","","")
names(var2.heading) <- c("vcat","low","med","high")
# Rbind the category headings and the table result data
table01 <- do.call("rbind", list(var1.heading, var1.df,
var2.heading, var2.df))
# Format the table for presentation
heading.list <- c("variable 1", "variable 2")
x <- formattable(table01,
align =c("l","c","c","c","c"),
list(vcat = formatter("span", style = x ~ ifelse(x %in% heading.list,
style(font.weight = "bold"), NA))))
My below attemps to automate the above code are either incomplete (a) or do not run properly (b)
# (a)
lapply(df, function(x) as.data.frame(table(x, df$cat)))
# (b)
myfxn <- function(x){
y <- as.data.frame(table(x, df$cat))
y <- reshape(y, idvar = "x", timevar = "Var2", direction = "wide")
names(y) <- c("vcat","low","med","high")
}
lapply(df, myfxn(x))
Any suggestions as to how I can automate this process for several more variables? Also, is there another way to insert category headings in the table other than manually creating an inserting a one line dataframe? Note that I inserted NAs in var1.heading since it's the first dataframe; when I tried inserting "" instead of blanks (like var2.heading), the subsequent dataframes wouldn't bind because they were factor vars, not character. Thank you very much in advance!
