Home > OS >  Whats the equivalent of this Python sequence in R?
Whats the equivalent of this Python sequence in R?

Time:10-15

I have this data frame with a few columns but the ones I'll be focusing here are accident_severity and day_of_week. Both them are categorical data and I'm trying to count the number of accidents in a given day of the week.

The way I'd do this in Python would be something like:

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

How can I accomplish this in R?

CodePudding user response:

The equivalent in tidyverse would be

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

Or using base R

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