gpt4 book ai didi

r:按多列分组并计数

转载 作者:行者123 更新时间:2023-12-02 15:14:33 26 4
gpt4 key购买 nike

我有以下数据框,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() 或来自 dplyr 的 group_by 来实现我的目标,但我是 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)

作为奖励,有 htmllatex 方法,可以轻松标记您的表格以包含在文章或报告中。

关于r:按多列分组并计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41306629/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com