Richi W
Richi W

Reputation: 3656

Efficient replication of data in R

I have data of the form

dates = as.Date(c("2015-04-07","2015-04-07","2015-04-08","2015-04-08"))
hour = rep(c(1,2),2)
value = c(3,6,8,4)
example.data = data.frame(dates,hour,value)

which gives

      dates hour value
1 2015-04-07    1     3
2 2015-04-07    2     6
3 2015-04-08    1     8
4 2015-04-08    2     4

and I would like to generate data for each quarter of an hour with constant fill-in.

The results should be

      dates hour  qhour value
1 2015-04-07    1   0     3
2 2015-04-07    1   1     3
3 2015-04-07    1   2     3
4 2015-04-07    1   3     3
5 2015-04-07    2   0     6
6 2015-04-07    2   1     6
7 2015-04-07    2   2     6

and so forth. Thus just replicating each value per hour for each quarter if an hour during this respective hour. Can this be done elegenantly using sqldf or something similar. Of course my data set if much much bigger than the example.

Upvotes: 1

Views: 38

Answers (1)

Roland
Roland

Reputation: 132706

Is this sufficiently efficient?

DF <- example.data[rep(seq_len(nrow(example.data)), each = 4),]
DF$qhour <- 0:3
#         dates hour value qhour
#1   2015-04-07    1     3     0
#1.1 2015-04-07    1     3     1
#1.2 2015-04-07    1     3     2
#1.3 2015-04-07    1     3     3
#2   2015-04-07    2     6     0
#2.1 2015-04-07    2     6     1
#2.2 2015-04-07    2     6     2
#2.3 2015-04-07    2     6     3
#3   2015-04-08    1     8     0
#3.1 2015-04-08    1     8     1
#3.2 2015-04-08    1     8     2
#3.3 2015-04-08    1     8     3
#4   2015-04-08    2     4     0
#4.1 2015-04-08    2     4     1
#4.2 2015-04-08    2     4     2
#4.3 2015-04-08    2     4     3

Upvotes: 3

Related Questions