I have date ranges that are grouped by two variables (id
and type
) that are currently stored in a data frame called data
. My goal is to ex
1) by Here is a three line answer using by
from the base of R. First we convert the dates to "Date"
class giving data2
. Then we apply f
which does the real work over each row and finally we rbind
the resulting rows together:
data2 <- transform(data, from = as.Date(from), to = as.Date(to))
f <- function(x) with(x, data.frame(id, type, date = seq(from, to, by = "day")))
do.call("rbind", by(data, 1:nrow(data), f))
2) data.table Using the same data2
with data.table we do it like this:
library(data.table)
dt <- data.table(data2)
dt[, list(id, type, date = seq(from, to, by = "day")), by = 1:nrow(dt)]
2a) data.table or alternately this where dt
is from (2) and f
is from (1):
dt[, f(.SD), by = 1:nrow(dt)]
3) dplyr with dplyr it gives a warning but otherwise works where data2
and f
are from (1):
data2 %>% rowwise() %>% do(f(.))
UPDATES Some improvements.