1

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

桌子图片

使用以下数据集

```{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()时遇到的主要问题是它们分别处理因子的每个级别,因此该表将产生一个计数,例如 for; .expsstablesTreat_Control == Treatment & Q1 == Yes & Q2 == Yes

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

谢谢,

4

1 回答 1

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))
     ))
于 2018-10-29T22:12:16.987 回答