I can’t find a really intuitive way of doing the most basic thing; creating a summary table with my base variables. The best method I’ve found is currently using tapply:
seed(200)
my_stats <- function(x){
if (is.factor(x)){
a <- table(x, useNA="no")
b <- round(a*100/sum(a),2)
# If binary
if (length(a) == 2){
ret <- paste(a[1], " (", b[1], " %)", sep="")
}
return(ret)
}else{
ret <- mean(x, na.rm=T)
if (ret < 1){
ret <- round(ret, 2)
}else{
ret <- round(ret)
}
return(ret)
}
}
library(rms)
groups <- factor(sample(c("Group A","Group B"), size=51, replace=T))
a <- 3:53
b <- rnorm(51)
c <- factor(sample(c("male","female"), size=51, replace=T))
res <- rbind(a=tapply(a, groups, my_stats),
b=tapply(b, groups, my_stats),
c=tapply(c, groups, my_stats))
latex(latexTranslate(res))
The res contains:
> res
Group A Group B
a "28" "28"
b "-0.08" "-0.21"
c "14 (56 %)" "14 (53.85 %)"
Now this works but it seems very complex and not the most elegant solution. I’ve tried to search for how to create descriptive tables but the all focus on the table(), prop.table(), summary() for just single variable or variables of the same kind.
My question: Is there a package/function that allows an easy way of creating a good-looking latex table? If so, please give a hint of how to get the above result.
Thanks!
If you rewrite your function so that it always returns a string
(it sometimes returns a string, sometimes a number, sometimes NULL),
you can call
ddplyon the data.frame, without having to specify all the columns.Since you want LaTeX tables, you may also want to try the following, which does not group the data, but adds sparkline histograms for the numeric variables.