Away may be:
as.data.frame(table(unlist(apply(df[-1], 1,
function(x) as.character(seq(as.Date(x[1], "%Y-%m-%d"),
as.Date(x[2], "%Y-%m-%d"), "1 day"))))))
Var1 Freq
1 2014-01-01 1
2 2014-01-02 2
3 2014-01-03 3
4 2014-01-04 3
5 2014-01-05 2
6 2014-01-06 1
, , . -, , as.Date apply. , , , , apply , , seq . -, seq "". -, . "".
f1 = function() {
as.data.frame(table(unlist(apply(df[-1], 1,
function(x) as.character(seq(as.Date(x[1], "%Y-%m-%d"),
as.Date(x[2], "%Y-%m-%d"), "1 day"))))))
}
f2 = function() {
df$start = as.numeric(as.Date(df$start, "%Y-%m-%d"))
df$stop = as.numeric(as.Date(df$stop, "%Y-%m-%d"))
res = as.data.frame(table(unlist(apply(df[-1], 1,
function(x) seq(x[1], x[2])))))
res$Var1 = factor(as.Date(as.numeric(as.character(res$Var1)),
origin = "1970-01-01"))
res
}
f1()
f2()
.
df = data.frame(person = paste("ID", 1:1e3, sep = ""),
start = as.Date(sample(Sys.Date() : (Sys.Date()+10), 1e3, T),
origin = "1970-01-01"))
df$stop = df$start + 5
head(df)
identical(f1(), f2())
library(microbenchmark)
microbenchmark(f1(), f2(), times = 10)