Given how long many things were each running for; calculating the total number of of things that were running over time?

Viewed 46

I have a few machines that start operating at the same time. I have a vector of numbers vec_num representing for how many units of time each machine was running for since it was started (there are no zero values).

I'm trying to find a way to efficiently calculate how many machines were running over time by making a vector of length(max(vec_num)) where each element represents a unit of time, and its value represents how many machines were running.

# For instance, take
vec_num <- c(1,1,4,3,1,10)

The ideal output would be a vector as generated from:

vec_num <- lapply(vec_num, function(x) {
  vec_zero <- rep(0, max(vec_num))
  vec_zero[1:x] <- 1
  return(vec_zero)
})

Reduce(`+`, vec_num)

>> 6 3 3 2 1 1 1 1 1 1

Where 6 machines were running at the first unit of time, 3 machines were running at the second and third, 2 at the fourth, and only one machine ran for 10. Think of the first index representing how many machines were running at the first unit of time, second index being the second unit of time, third index being the third, and so fourth.

However, this way is computationally and memory inefficient, and doesn't scale when there are hundreds of thousands of machines that are running for several thousand units of time. Is there a more efficient way to go about calculating this?

2 Answers

Here is an option:

rev(cumsum(rev(tabulate(vec_num))))
#[1] 6 3 3 2 1 1 1 1 1 1

We can use sequence + table

as.integer(table(sequence(vec_num)))
#[1] 6 3 3 2 1 1 1 1 1 1
Related