如何获取R中Hmisc包summaryM生成表格的LaTeX源代码?
问题:从Hmisc包summaryM结果导出LaTeX源代码
我用Hmisc包生成了统计表格,但调用latex(f)只显示表格,无法获取可复制的LaTeX源代码,想要得到类似xtable包xtable()输出的LaTeX代码用于其他文件。以下是我的R代码:
library(Hmisc) options(digits=3) set.seed(173) sex <- factor(sample(c("m","f"), 500, rep=TRUE)) country <- factor(sample(c('US', 'Canada'), 500, rep=TRUE)) age <- rnorm(500, 50, 5) sbp <- rnorm(500, 120, 12) label(sbp) <- 'Systolic BP' units(sbp) <- 'mmHg' treatment <- factor(sample(c("Drug","Placebo"), 500, rep=TRUE)) treatment[1] sbp[1] <- NA # Generate a 3-choice variable; each of 3 variables has 5 possible levels symp <- c('Headache','Stomach Ache','Hangnail', 'Muscle Ache','Depressed') symptom1 <- sample(symp, 500,TRUE) symptom2 <- sample(symp, 500,TRUE) symptom3 <- sample(symp, 500,TRUE) Symptoms <- mChoice(symptom1, symptom2, symptom3, label='Primary Symptoms') table(as.character(Symptoms)) # Note: In this example, some subjects have the same symptom checked # multiple times; in practice these redundant selections would be NAs # mChoice will ignore these redundant selections f <- summaryM(age + sex + sbp + Symptoms ~ treatment, test=TRUE)
解决方法
有两种简单方式获取LaTeX源代码:
- 输出到文件
调用latex()时指定file参数,将LaTeX代码写入到指定的.tex文件中,直接打开文件即可复制代码:
latex(f, file = "summary_table.tex")
- 直接在控制台输出
用capture.output()捕获latex(f)的输出,再用cat()打印出来,就能在控制台看到完整的LaTeX源代码:
cat(capture.output(latex(f)), sep = "\n")
这样就能得到可直接复制使用的LaTeX代码,和xtable包的输出效果一致。
内容的提问来源于stack exchange,提问作者Adrian
相关产品推荐
相关产品推荐

