Suppose we have the following dataset.
1 2 3 4 5 6 7 8 9 10 11 12 |
library(tidyverse) ##### Creating Sample Data ##### Name <- as.character(c("Abbey", "Brian", "Connie", "Dan", "Ethan")) GPA <- c(3.0, 2.8, 2.1, 4.0, NA) Grade <- c(3, 4, NA, NA, 6) State <- c("AL", NA, NA, NA, "CA") Jello_Consumption <- c(1,2,3,4,5) data <- data.frame(Name, GPA, Grade, State, Jello_Consumption, stringsAsFactors = FALSE) data |
1 2 3 4 5 6 7 |
> data Name GPA Grade State Jello_Consumption 1 Abbey 3.0 3 AL 1 2 Brian 2.8 4 <NA> 2 3 Connie 2.1 NA <NA> 3 4 Dan 4.0 NA <NA> 4 5 Ethan NA 6 CA 5 |
We can add a cumulative Jello consumption column using cumsum() .
1 2 3 4 |
##### Cumsum ##### data <- mutate(data, Cumulative = cumsum(Jello_Consumption)) data |
1 2 3 4 5 6 7 |
> data Name GPA Grade State Jello_Consumption Cumulative 1 Abbey 3.0 3 AL 1 1 2 Brian 2.8 4 <NA> 2 3 3 Connie 2.1 NA <NA> 3 6 4 Dan 4.0 NA <NA> 4 10 5 Ethan NA 6 CA 5 15 |