【问题标题】:Whats the equivalent of this Python sequence in R?R 中这个 Python 序列的等价物是什么?
【发布时间】:2021-12-03 07:06:31
【问题描述】:

我有这个包含几列的数据框,但我将在这里重点关注的是accident_severityday_of_week。它们都是分类数据,我正在尝试计算一周中给定日期的事故数量。

我在 Python 中执行此操作的方式类似于:

df.value_counts().groupby(['accident_severity']).sum()

如何在 R 中完成此操作?

【问题讨论】:

    标签: python r dataframe


    【解决方案1】:

    tidyverse 中的等价物是

    library(dplyr)
    df %>%
        count(day_of_week, accident_severity) %>%
        group_by(accident_severity) %>%
        summarise(n = sum(n), .groups = 'drop')
    

    或使用base R

    rowSums(table(df[c("day_of_week", "accident_severity")]))
    

    【讨论】:

    • 很抱歉打扰您,但您能解释一下 'n = sum(n)' 中的 'n' 是从哪里来的吗?
    • @Marcos count 默认创建一个名为 n 的汇总列。如果要更改名称,请在count中指定name = "n1"
    猜你喜欢
    • 2021-06-19
    • 2017-12-25
    • 1970-01-01
    • 1970-01-01
    • 2019-02-12
    • 2023-03-25
    • 2011-03-19
    • 2021-02-14
    • 2011-11-17
    相关资源
    最近更新 更多