For datasets where a variable corresponds to a group and another to a time, a useful function would be to add rows for missing dates, making missing observation explicit.
mydata <- data_frame(
name = c("john","john","john","john","mary","chris","chris","chris"),
year = c(1999, 2000, 2001, 2003, 2001, 1998, 1999, 2003),
score = rnorm(8)
)
texpand(mydata, name, year) is different from expand(mydata, name, year) in that it adds all dates between the min and the max of the last argument (2002 in the previous dataset)
This defines texpand:
#' @export
texpand <- function(data, ..., period = 1L) {
dots <- lazyeval::lazy_dots(...)
texpand_(data, dots, period = period)
}
#' @export
texpand_ <- function(data, dots, ..., period = 1L) {
UseMethod("texpand_")
}
#' @export
texpand_.data.frame <- function(data, dots, ..., period = 1L) {
dots <- lazyeval::as.lazy_dots(dots)
if (length(dots) == 0)
return(data.frame())
iddots <- dots[-length(dots)]
pieces <- lapply(iddots, unique_vals, data = data)
timedot <- dots[length(dots)]
time <- dplyr::select_(data, .dots = timedot)[[1]]
timev <- seq_time(time, period = period)
check <- (time - timev[1]) %% period
if (sum(check)){
stop("Time vector is not a regular sequence")
}
pieces[[length(pieces)+1]] <- data.frame(timev)
Reduce(cross_df, pieces)
}
#' @export
texpand_.tbl_df <- function(data, dots, ..., period = period) {
dplyr::tbl_df(NextMethod())
}
seq_time <- function(x, period) {
attrs <- attributes(x)
rng <- range(x, na.rm = TRUE)
attributes(rng) <- attrs
out <- seq(rng[1], rng[2], by = period)
}
Another direction than creating texpand and tlag would be to define a new class of dataset, tbl_panel, which is a group + time. When setting the panel type, this checks that the time variable has no missing value and that there are no duplicate times by group. Then tidyr/dplyr has a special expand and a special lag for them.
For datasets where a variable corresponds to a group and another to a time, a useful function would be to add rows for missing dates, making missing observation explicit.
texpand(mydata, name, year)is different fromexpand(mydata, name, year)in that it adds all dates between the min and the max of the last argument (2002 in the previous dataset)This defines
texpand:Another direction than creating
texpandandtlagwould be to define a new class of dataset, tbl_panel, which is a group + time. When setting the panel type, this checks that the time variable has no missing value and that there are no duplicate times by group. Then tidyr/dplyr has a special expand and a special lag for them.