我有以下数据框df
:
LeftOrRight SpeedCategory NumThruLanes
R 25to45 3
L 45to62 2
R Gt62 1
我想将其按SpeedCategory分组并遍历其他列,以获取每个速度类别中每个唯一代码的频率-像这样:
25to45 45to62 Gt62
LeftOrRight L 0 1 0
R 1 0 1
NumThruLanes 1 0 0 1
2 0 1 0
3 1 0 0
我最接近的是:
for (col in df){
tbl <- table(col, df$SpeedCategory)
print(tbl)
}
打印出以下内容(首先是SpeedCategory,然后是NumThruLanes):
col 25to45 45to62 Gt62
L 0 1 0
R 1 0 1
col 25to45 45to62 Gt62
1 0 0 1
2 0 1 0
3 1 0 0
我很确定我可以使用aggregate()
或也许使用group_by来实现我的目标dplyr
,但是我是R的新手,无法弄清楚语法。在pandas
我会使用一个,MultiIndex
但我不知道什么是R等效,所以很难谷歌。
我想尝试一次或循环执行所有操作,因为我要遍历十多个列。
该tables
软件包使以特定方式格式化表格变得容易。语法需要一些时间来适应,但是对于这个问题,它很简单:
exd <- read.table(text = "LeftOrRight SpeedCategory NumThruLanes
R 25to45 3
L 45to62 2
R Gt62 1", header = TRUE)
## to get counts by default we need everything to be categorical
exd$SpeedCategory <- factor(exd$SpeedCategory)
library(tables)
tabular(LeftOrRight + NumThruLanes ~ SpeedCategory, data = exd)
## SpeedCategory
## 25to45 45to62 Gt62
## LeftOrRight L 0 1 0
## R 1 0 1
## NumThruLanes 1 0 0 1
## 2 0 1 0
## 3 1 0 0
如果您有很多要迭代的列,则可以通过编程方式构造公式,例如,
tabular(as.formula(paste(paste(names(exd)[-2], collapse = " + "),
names(exd)[2], sep = " ~ ")),
data = exd)
作为奖励,也有html
和latex
方法,使其易于标记你的表最多收录的文章或报告英寸
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句