r - 计算表中的出现次数并在 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` |
我的问题是:有没有更好的方法来做到这一点?当您有许多因素组合并且规模很差时,这种方法会变得非常乏味。
解决方案
我们可以使用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()
```
推荐阅读
- c# - The model item passed into the ViewDataDictionary is of type Models but needs ViewModels
- javascript - 图像未加载(Phaser)
- javascript - 使用 node.js 将上传的文件发送到客户端
- java - Cannot create TypedQuery for query with more than one return using requested result type, despite having correct DTO
- go - "transaction type not supported" When trying to deploy a simple contract using Go-Ethereum, Solidity, Go. Doesn't happen in Remix
- amazon-web-services - Assistance with Header based routing with AWS App Mesh
- java - How to have different color for line and text in StrikethroughSpan?
- python - Problem with grouping and counting in python
- google-apps-script - How to import csv file from the link in gmail to google sheet with apps script?
- github - Can I prevent Github Actions from updating status checks?