How to get tally (rolling sum) by group in R?

KC Ray

I would like to create a column called "tally" in my dataset that takes sums the count of each type and rank.

type <- c("A","A","A","B","B","C")
rank <- c("low", "med", "high","med", "high", "low")
count <- c(9,20,31,2,4,14)

df <- data.frame(type, rank, count)

My desired output would be:

type rank count tally
1    A  low     9     9
2    A  med    20    29
3    A high    31    60
4    B  med     2     2
5    B high     4     6
6    C  low    14    14 

I guess another way to describe it would be a rolling sum (where it takes into account the low to high order)? I have looked around but I can't find any good functions to do this. Ideally, I could have a for loop that would allow me to get this "rolling sum" by type.

akrun

We can use cumsum after grouping by 'type'

library(dplyr)
df <- df %>%
   group_by(type) %>%
    mutate(tally = cumsum(count)) %>%
    ungroup

-output

# A tibble: 6 x 4
  type  rank  count tally
  <chr> <chr> <dbl> <dbl>
1 A     low       9     9
2 A     med      20    29
3 A     high     31    60
4 B     med       2     2
5 B     high      4     6
6 C     low      14    14

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Apply a rolling sum by group in R

From Dev

Pandas Group then rolling and sum get wrong results

From Dev

Generating a rolling tally based on criterion (R)

From Dev

rolling sum by group

From Dev

Calculate rolling sum by group

From Dev

R - Rolling sum based on dates, with a condition per group

From Dev

R dplyr rolling sum

From Dev

Rolling sum in R

From Dev

Getting Rolling Sum per Group

From Dev

Rolling sum within group boundaries

From Dev

R, how to tally by two columns?

From Dev

How to Reverse Rolling Sum?

From Dev

Rolling difference in group and divivded by group sum in Pandas

From Dev

Oracle SQL: How to get rolling SUM of only last 3 months?

From Dev

How to Get Rolling Sum Without Returning NA's

From Dev

Rolling sum with double indexing in R

From Dev

Generating a rolling tally based on criterion

From Dev

how to get my python tally app to subtract?

From Dev

Compute rolling sum shifted for each group

From Dev

Pandas rolling conditional sum on time and group

From Dev

How to identify and tally intersection items in R

From Dev

Rolling difference in group_by in R

From Dev

Tally XML Get GST Rate Setup by Stock Group

From Dev

How to perform rolling sum in BigQuery

From Dev

How to do a rolling sum in PySpark?

From Dev

How to perform rolling sum on pandas dataframe with group by for last 365 days only

From Dev

How get multiple SUM() for different columns with GROUP BY

From Dev

How to get cumulative sum of unique IDs with group by?

From Dev

How to get Sum with group by in Django query