如何在R中创建嵌套表

时间:2018-10-29 17:47:14

标签: r expss

我正在努力弄清楚如何创建下表;

Image of table

使用以下数据集

```{r}
df<-data.frame(ID=c(1,2,3,4,5,6),
       Treat_Cont = c("Treatment", "Treatment", "Treatment", "Control", "Control", "Control"),
       Q1 = c("Yes", "No", NA, "Yes", "No", NA),
       Q2 = c("Yes", "No", NA, "Yes", "No", NA)
       )
```

我使用table()expss包或tables包的主要问题是它们分别处理每个级别的因子,因此表将针对例如Treat_Control == Treatment & Q1 == Yes & Q2 == Yes

当前,我处于不确定我的问题是否是数据结构之一的阶段,这意味着我应该重塑数据集,或者是否缺少实现此结果的函数或参数。

谢谢

1 个答案:

答案 0 :(得分:1)

expss解决方案。我认为代码不太简洁:

library(expss)
df = data.frame(ID=c(1,2,3,4,5,6),
               Treat_Cont = c("Treatment", "Treatment", "Treatment", "Control", "Control", "Control"),
               Q1 = c("Yes", "No", NA, "Yes", "No", NA),
               Q2 = c("Yes", "No", NA, "Yes", "No", NA)
)

df %>% 
    tab_total_row_position("none") %>% # suppress totals
    tab_rows("|" = Treat_Cont) %>%  # "|" suppress var. labels
    tab_cols(total(label = "|")) %>% # "|" suppress var. labels
    # if_na add values for NA
    tab_cells("|" = if_na(Q1, "<NA>")) %>% # "|" suppress var. labels
    tab_stat_cases(label = "Q1") %>% # calculate stats
    tab_cells("|" = if_na(Q1, "<NA>")) %>% # "|" suppress var. labels
    tab_stat_cases(label = "Q2") %>% # calculate stats
    tab_pivot(stat_position = "inside_columns") %>% # labels reposition
    tab_transpose() # transpose table

更新:较短的解决方案。

df %>% 
    calculate(
        cro(Treat_Cont %nest% if_na(Q1, "<NA>"), list("Q1"), total_row_position = "none") %merge%
            cro(Treat_Cont %nest% if_na(Q2, "<NA>"), list("Q2"), total_row_position = "none")
    ) %>% 
    tab_transpose()

以R为底的简短解决方案:

with(df, 
     rbind(
         "Q1" = table(Treat_Cont:addNA(Q1)),
         "Q2" = table(Treat_Cont:addNA(Q2))
     ))