0

I want to generate an accumulating total duration based on each additional value in the new vector.

I can manually display what I'm trying to achieve but cannot complete this task with code. The aim is to create a script that will automate the 'total_duration' column based on the 'duration' column.

duration=c(1.5,8.9,3,6.2)
total_duration=c(1.5,10.4,13.4,19.6)
duration_df=data.frame(duration,total_duration)
Syncrossus
  • 570
  • 3
  • 17
Sparky
  • 349
  • 1
  • 12

2 Answers2

1

You can achieve this with the base function cumsum()

total_duration = cumsum(duration)
[1]  1.5 10.4 13.4 19.6
MrNetherlands
  • 920
  • 7
  • 14
1

You're looking for the cumsum function. Modifying your code gets us:

duration <- c(1.5,8.9,3,6.2)
total_duration <- cumsum(duration)
duration_df <- data.frame(duration,total_duration)

If you want to modify an existing dataframe df, you can do df$b <- cumsum(df$a).

Syncrossus
  • 570
  • 3
  • 17