Search code examples
rdataframecumsum

How to add new vector that includes 0 and cumsum to dataframe?


I want to add a new vector to a dataframe based on cumsum of previous column but starting from 0.

I've tried to create a vector with 0 and then the cumsum function but I have an additional row now from this. I've tried to remove the additional row but cannot.

mydata$time<-c(0,cumsum(mydata$duration))

Error in $<-.data.frame(*tmp*, time, value = c(0, 5, 9, 15.4, : replacement has 1138 rows, data has 1137


Solution

  • We may need to remove the last element and then do the cumulative sum, otherwise, it would have a mismatch between the number of rows of the original column and the new vector created

    cumsum(c(0, mydata$duration[-nrow(mydata)]))