分类变量的统计摘要-学术论文

时间:2019-08-05 02:20:17

标签: r function summary

我正在为R中的分类变量准备摘要统计量,以放入学术论文中。我正在寻找这样的输出:

Create summary table of categorical variables of different lengths 但是,我找不到分类变量的函数。

这是我的小例子:

library(dplyr)
library(stargazer)

mtcars %>%
  mutate(mpg_cat = ifelse(mpg > mean(mpg), 1,0)) %>%
  mutate(mpg_cat= as.factor(mpg_cat)) %>%
  mutate(cyl_cat= as.factor(cyl)) %>%
  select(cyl_cat, mpg_cat ) %>%
  function() %>% ##???
  stargazer(summary=FALSE, rownames=FALSE,
            #note you have to specify type
            type = "html",
            #note that the argument is "out" not "file"
            out="temp.doc")

这是我脑海中的输出: https://i.stack.imgur.com/CIdIa.jpg

2 个答案:

答案 0 :(得分:1)

假设您有数据来填充模板,就像使用库kableExtra

https://haozhu233.github.io/kableExtra/awesome_table_in_pdf.pdf

(请参阅第14-20页)

最好学习如何处理表,该库也使用您已经知道的%>%符号。

答案 1 :(得分:0)

我想到了这段代码:

mtcars %>%
  mutate(mpg_cat = ifelse(mpg > mean(mpg), "Yes","No")) %>%
  mutate(mpg_cat= as.factor(mpg_cat)) %>%
  mutate(cyl_cat= as.factor(cyl)) %>%
  select(cyl_cat, mpg_cat ) %>%

  summary() %>%
  as.data.frame() %>%
  select(-Var1) %>%
  rename(Variable=Var2) %>%
  filter(! is.na(Freq) ) %>%
  separate(Freq, c("Level", "Freq."),sep=":" ) %>%
  mutate(Freq. = as.integer(Freq.)) %>%
  mutate(Total = nrow(mtcars)) %>%
  mutate(Perc. = Freq.*100/Total)  %>%
  select (-Total)  %>%

  stargazer(summary=FALSE, rownames=FALSE,
            #note you have to specify type
            type = "html",
            #note that the argument is "out" not "file"
            out="mtcars.doc")