我想使用tables-package中的tabular()-function对两个变量(例如v1和v2)进行交叉制表,并在表中显示chisq--function的p值。很容易得到交叉表,但我不能得到表内的p值。这就是我一直在尝试的,但没有任何运气:

\documentclass{article}
\begin{document}
<<echo=TRUE,message=FALSE>>=
library(Hmisc)
library(tables)
v1 <- sample(letters[1:2],200,replace=TRUE)
v2 <- sample(month.name[1:3],200,replace=TRUE)
df <- data.frame(v1,v2)
@
It is straight forward to get the crosstabulation:
<<results='asis'>>=
latex( tabular( Factor(v1) ~ Factor(v2) , data=df) )
@
But I cant get the p-value inside the table:
<<results='asis'>>=
latex( tabular( Factor(v1)*chisq.test(v1,v2)$p.value ~ Factor(v2) , data=df) )
@
\end{document}发布于 2013-05-13 06:03:41
我不知道如何在tables::tabular中做到这一点,但是假设您已经将您的系统配置为通过latex()生成pdf文件,那么在Hmisc::summary.formula.reverse中就可以做到。我必须搜索Rhelp归档文件,才能找出latex参数列表中需要包含'exclude1‘参数。返回文档后,虽然我以为是在阅读summary.rms的帮助页面,但exclude1确实出现在latex.summary.formula.reverse的用法示例中
library(Hmisc)
latex(summary( v2 ~ v1, data=df, method="reverse" ,test=TRUE), exclude1=FALSE)

如果您希望通过将输出分配给指定的文件来将latex输出嵌入到较长的文档中,则可以“一路上”截取latex输出。
latex(summary( v2 ~ v1, data=df, method="reverse" ,test=TRUE), exclude1=FALSE, file="")
#--------
% latex.default(cstats, title = title, caption = caption, rowlabel = rowlabel, col.just = col.just, numeric.dollar = FALSE, insert.bottom = legend, rowname = lab, dcolumn = dcolumn, extracolheads = extracolheads, extracolsize = Nsize, ...)
%
\begin{table}[!tbp]
\caption{Descriptive Statistics by v2\label{summary}}
\begin{center}
\begin{tabular}{lcccc}
\hline\hline
\multicolumn{1}{l}{}&\multicolumn{1}{c}{February}&\multicolumn{1}{c}{January}&\multicolumn{1}{c}{March}&\multicolumn{1}{c}{Test Statistic}\tabularnewline
&\multicolumn{1}{c}{{\scriptsize $N=56$}}&\multicolumn{1}{c}{{\scriptsize $N=73$}}&\multicolumn{1}{c}{{\scriptsize $N=71$}}&\tabularnewline
\hline
v1~:~a&43\%~{\scriptsize~(24)}&47\%~{\scriptsize~(34)}&44\%~{\scriptsize~(31)}&$ \chi^{2}_{2}=0.21 ,~ P=0.901 $\tabularnewline
~~~~b&57\%~{\scriptsize~(32)}&53\%~{\scriptsize~(39)}&56\%~{\scriptsize~(40)}&\tabularnewline
\hline
\end{tabular}
\end{center}
Numbers after percents are frequencies.\\\noindent Test used:\\Pearson test\end{table}发布于 2017-11-14 00:51:59
还可以通过xtable()将卡方统计数据中的文本粘贴到标题中。例如:
#sample data
var1<-sample(c('A', 'B'), 10, replace=T)
var2<-sample(c('Red', 'Blue'), 10, replace=T)
#join in frequency table
tab<-table(var1, var2)
#conduct chisq.test
test<-chisq.test(tab)
#show values of chisq.test()
name(test)
#Use xtable, use print.xtable for further manipulations
out<-xtable(tab, caption=paste('Important table, chi-squared =', test$statistic, ', p=', test$p.value,',' ,test$parameter, 'df', sep=' '))
#print
out https://stackoverflow.com/questions/16510666
复制相似问题