【问题标题】:Count occurences in table and show in rmarkdown, scalability [duplicate]计算表中的出现次数并在 rmarkdown 中显示,可扩展性 [重复]
【发布时间】:2018-05-18 08:05:39
【问题描述】:

我们以下面的数据框为例:

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` |

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

【问题讨论】:

  • 做什么?计算出现次数或在表格中显示它们?这是两个截然不同的问题。
  • 要计算出现次数,下面发布的table 解决方案似乎是正确的方法。很抱歉有歧义。

标签: r dataframe r-markdown


【解决方案1】:

我们可以使用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()
```

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-12
    • 2011-05-07
    • 1970-01-01
    • 2018-07-05
    • 2017-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多