[英]How to obtain a descriptive LateX table of continuous variable stratified by groups in R
dat <- data.frame(outcome = rnorm(25),
sex = sample(c("F", "M"), 25, replace = TRUE),
age_group = sample(c(1, 2, 3), 25, replace = TRUE))
> head(dat)
outcome sex age_group
1 1.1423 F 2
2 0.0998 M 1
3 -1.6305 F 2
4 -1.6759 F 1
5 0.3825 F 2
6 0.7274 F 3
我有一個具有連續outcome
變量的數據集。 我想獲得一個 LaTeX 表,該表包含按sex
和age_group
分層的此變量的描述性統計信息。 我希望它看起來像這樣(它不必具有平均值(SD),但我希望按年齡組和性別分層的結果布局):
我試過Hmisc
package:
library(Hmisc)
output <- summaryM(outcome ~ sex + age_group, data = dat, test = TRUE)
latex(output, file = "")
但是 output 看起來和我想要的很不一樣:
我比較熟悉gt package,強烈推薦大家學習使用。
這是一個使用 gt package 和您的示例代碼的解決方案。
#Install the package and load the dependencies. Here Ill be using dplyr to
#group by variables.
install.packages("gt")
library(gt)
library(dplyr)
dat <- data.frame(outcome = rnorm(25),
sex = sample(c("F", "M"), 25, replace = TRUE),
age_group = sample(c(1, 2, 3), 25, replace = TRUE))
head(dat) %>%
#Group by desired column
group_by(sex) %>%
#Create a gt table with the data frame
gt() %>%
#Rename columns
cols_label(outcome = "",
sex = "Sex",
age_group = "Cohort") %>%
#Add a table title
#Notice the `md` function allows to write the title using markdown syntax (which allows HTML)
tab_header(title = md("Table 1: Descriptive Statistics (N = 7")) %>%
#Add a data source footnote
tab_source_note(source_note = "Data: Stackoverflow question 7508787 [user: Adrian]")%>%
#you can customize the table´s body and lines as well using the tab_option
#function and tab_style function.
tab_options(row.striping.include_table_body = FALSE) %>%
tab_style(style = cell_borders(
sides = c("top"),
color = "black",
weight = px(1),
style = "solid"),
locations = cells_body(
columns = everything(),
rows = everything()
)) %>%
#Finally you can create summaries with different statistics as wanted.
summary_rows(
groups = TRUE,
columns = outcome,
fns = list(
average = "mean",
total = "sum",
SD = "sd")
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.