Create a Cumulative Sum Column in R

One of the first things I learned in R was how to use basic statistics functions like sum(). However, what if you want a cumulative sum to measure how something is building over time–rather than just a total sum to measure the end result? It turns out there is a function for cumulative sum, called cumsum(). Here’s out to use it…

### create (or import) a data frame of totals
	product_sales <- data.frame("Day" = c(1:10),"Sales" = c(100,200,150,120,130,145,90,150,180,190))

### add cumulative column to the data frame
	product_sales[,"cum_sales"] <- cumsum(product_sales$Sales)

### print data frame
	product_sales

It’s that simple. Here’s how the output looks from the dummy data frame I created:
Output of cumsum in R

Create a 52 Week Vector of Dates in R

If you want to keep a weekly log of anything from your body weight to your company’s product sales, it might be easier to have a column of all the dates you’ll need over the next year as a template. That way, when you reach the time each week that you enter your data (say, Monday morning), you can enter the data beside a date that is already there in the adjacent column.

Here’s how to create a vector of weekly dates spanning out over an entire year.

### initialize vector as today's date; if you want to start with a different date, use as.Date("YYYY-MM-DD") in place of Sys.Date() in the code
week_ending = Sys.Date()

### write a for loop on a sequence of next 52 weeks
for(i in seq(from = 1, by = 7, length.out = 52)) {
week_ending[i] = (week_ending - 1) + i
}

### remove NAs from the vector that is created
week_ending = week_ending[!is.na(week_ending)]

### print week_ending to generate a vector of the next 52 weeks, beginning with today's date
week_ending

That’s it. You now have a vector with the length of 52, containing dates for every week over the next year beginning with today. See the code and R output below.

R Output for Vector of Weeks

Feel free to grab this code if it’s useful, and please fix it if there’s a better way!