1

Assume I need calculate the cumulative value based on other column in the same row and also the value from same column but previous row. Example: to obtain cumulative time based on time intervals.

> data <- data.frame(interval=runif(10),time=0)
> data
     interval time
1  0.95197753    0
2  0.73623490    0
3  0.63938696    0
4  0.32085833    0
5  0.92621764    0
6  0.02801951    0
7  0.09071334    0
8  0.60624511    0
9  0.35364178    0
10 0.79759991    0

I can generate the cumulative value of time using the (ugly) code below:

for( i in 1:nrow(data)){
    data[i,"time"] <- data[i,"interval"] + ifelse(i==1,0,data[i-1,"time"])
}

> data
     interval      time
1  0.95197753 0.9519775
2  0.73623490 1.6882124
3  0.63938696 2.3275994
4  0.32085833 2.6484577
5  0.92621764 3.5746754
6  0.02801951 3.6026949
7  0.09071334 3.6934082
8  0.60624511 4.2996533
9  0.35364178 4.6532951
10 0.79759991 5.4508950

Is it possible to do this without the for iteration, using a single command?

Denio Mariz
  • 1,065
  • 1
  • 10
  • 12

2 Answers2

0

As Ronak says and you do this as well using dplyr and the pipe:

library(dplyr)
data <- data %>%
  mutate(time = cumsum(interval))
Paul van Oppen
  • 1,443
  • 1
  • 9
  • 18
0

Maybe what you are looking for is cumsum():

library(tidyverse)
data <- data %>%
  mutate(time = cumsum(interval))
cheetahfly
  • 31
  • 2