首页 > 解决方案 > 计算表中的出现次数并在 rmarkdown 中显示,可扩展性

问题描述

让我们以以下数据框为例:

df <- data.frame(state = c('up', 'up', 'up', 'down', 'down', 'up', 'down', 'down'), type = c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'))

要计算 A/B 和 up/down 的每种可能组合出现的次数,我将执行以下操作:

a1 <- nrow(subset(subset(df, state == 'up'), type == 'A'))
a2 <- nrow(subset(subset(df, state == 'down'), type == 'A'))
a3 <- nrow(subset(subset(df, state == 'up'), type == 'B'))
a4 <- nrow(subset(subset(df, state == 'down'), type == 'B'))

为了表明在 Rmarkdown 表中,我将执行以下操作:

| State/type     |   A    |    B   | 
|:--------------:|:------:|:------:|
| Up             | `r a1` | `r a3` |
| Down           | `r a2` | `r a4` |

我的问题是:有没有更好的方法来做到这一点?当您有许多因素组合并且规模很差时,这种方法会变得非常乏味。

标签: rdataframer-markdown

解决方案


我们可以使用table

tbl <- table(df)

并将其转换为data.frame

as.data.frame.matrix(tbl)

或者如果我们也需要“状态”列(而不是上面的行名)

library(tidyverse)
count(df, state, type) %>% 
              spread(type, n)

在 rmarkdown 中,上面可以用作

```{r echo = FALSE, include = FALSE, cache=FALSE}
df <- data.frame(state = c('up', 'up', 'up', 'down', 'down', 'up', 
   'down', 'down'), type = c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'))
library(dplyr)
library(tidyr)
library(kableExtra)
out <- count(df, state, type) %>% 
              spread(type, n)

```



```{r code1, results = 'asis', echo = FALSE}
kable(out, "html") %>%
  kable_styling()
```

推荐阅读