Increase the data resolution of a vector of episode durations without a loop function

Viewed 31

I have a vector Z<-c(0, 0, 0, 0, 360, 0, 0, 0, 0) of a daily duration of events (each element of the vector is a day and the value of each element is the episode duration in minutes) so that each element of the vector is [0,1440].

I would like to convert the vector from daily minutes to 1 minute intervals (so that each element of the vector is a 1 minute interval) and the value of each element would be [0,1]. I came up with the following solution

Z<-c(0, 0, 0, 0, 360, 0, 0, 0, 0)
c.Z<-1440- Z

temp<-NULL
for (i in 1:length(Z)){
temp<-c(temp, c(rep(1,Z[i]), rep(0,c.Z[i])))    
}

temp

> sum(temp)==sum (Z)
[1] TRUE
> length(temp)==1440*length(Z)
[1] TRUE

Is there a faster, nicer or quicker way to do this without the for function?

1 Answers

You can use rep in this fashion :

temp2 <- rep(rep(c(1, 0), length(Z)), c(rbind(Z, 1440-Z)))
identical(temp, temp2)
#[1] TRUE

The first rep repeats 1, 0 for each day.

rep(c(1, 0), length(Z))
#[1] 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0

We use c(Z, 1440-Z) to create times argument for second rep.

c(rbind(Z, 1440-Z))
#[1]  0 1440 0 1440  0 1440  0 1440 360 1080  0 1440  0 1440 0 1440  0 1440
Related