[英]How to calculates the descriptive statistics for both numeric and categorical variables in R?
[英]Descriptive tables - how to create a table containing both numeric and categorical variables
我找不到最直觀的方式來做最基本的事情; 用我的基本變量創建一個匯總表。 我發現的最好方法是當前使用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))
資源包含:
> res
Group A Group B
a "28" "28"
b "-0.08" "-0.21"
c "14 (56 %)" "14 (53.85 %)"
現在可以使用,但似乎非常復雜,而不是最優雅的解決方案。 我試圖搜索如何創建描述性表,但是所有這些都只針對單個變量或同類變量的table(),prop.table(),summary()。
我的問題:是否有一個軟件包/功能可以輕松創建美觀的乳膠表? 如果是這樣,請提示如何獲得上述結果。
謝謝!
如果要創建包含分類變量和連續變量的匯總表,則應查看“ tableone”包。
這是它可以做什么的示例https://rpubs.com/kaz_yos/tableone-vignette 。 這是pdf文檔: https : //cran.r-project.org/web/packages/tableone/tableone.pdf
我希望這有幫助。
您要問的是開放式的,因為您很可能在構成“漂亮的LaTeX表”方面與我意見不一致。
例如,我可能更喜歡按行而不是按列進行組織:
require(plyr)
require(xtable)
dat <- data.frame(a,b,c,groups)
xtable(ddply(dat,.(groups),summarise,a = my_stats(a),
b = my_stats(b),
c = my_stats(c)))
\begin{table}[ht]
\begin{center}
\begin{tabular}{rlrrl}
\hline
& groups & a & b & c \\
\hline
1 & Group A & 28.00 & 0.14 & 13 (52 \%) \\
2 & Group B & 28.00 & -0.00 & 13 (50 \%) \\
\hline
\end{tabular}
\end{center}
\end{table}
當然,如果您同時查看?xtable
和?print.xtable
,其中的大部分內容都是可自定義的。
如果重寫函數以使其始終返回一個字符串(有時返回一個字符串,有時返回一個數字,有時返回NULL),則可以在ddply
上調用ddply,而不必指定所有列。
f <- function(u) {
res <- "?"
if(is.factor(u) || is.character(u)) {
u <- table(u, useNA = "no")
if (length(u) == 0 || sum(u) == 0) { res <- "NA" }
else { res <- sprintf( "%0.0f%%", 100 * u[1] / sum(u) ) }
} else {
u <- mean(u, na.rm=TRUE)
if(is.na(u)) { res <- "NA" }
else { res <- sprintf( ifelse( abs(u) < 1, "%0.2f", "%0.0f" ), u ) }
}
return( res )
}
# Same function, for data.frames
g <- function(d) do.call( data.frame, lapply(d, f) )
library(plyr)
ddply(data.frame(a,b,c), .(groups), g)
由於您需要LaTeX表,因此您可能還想嘗試以下方法,該方法不對數據進行分組,而是為數字變量添加迷你圖直方圖。
library(Hmisc)
latex(describe(d), file="")
查看tables
包,這可能會使此過程更簡單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.