関数create_mem_ts
(メンバーシップ時系列)は、質問に投稿された目的の出力を生成します。
create_mem_ts <- function (ctime, added, removed, current) {
# Create a time-series of membership of a set.
# Inputs:
## ctime: Time of changes in set.
## An atomic vector of a time-series class or otherwise,
##
## interpretable as a time-series in descending order (for e.g.
## `t-1`, `t-2`, `t-3` etc.
##
## Is an index of when the changes in membership happened in time.
## Allows repeats but no NAs.
## added: Member(s) added to the set.
## An atomic vector or a list of the same length as ctime.
##
## If an atomic vector, represents exactly one member added at
## the corresponding ctime.
##
## If a list, represents multiple members added at corresponding
## ctime.
## removed: Member(s) removed from the set.
## An atomic vector or a list of the same length as ctime.
##
## If an atomic vector, represents exactly one member removed at
## the corresponding ctime.
##
## If a list, represents multiple members removed at the
## corresponding ctime.
## current: Current membership of the set.
## An atomic vector listing the current membership of the set.
# Output:
## A list of the same length as ctime named by values in ctime (coerced to
## character by the appropriate method).
stopifnot(is.atomic(ctime),
is.atomic(added) || is.list(added),
is.atomic(removed) || is.list(removed))
if (any(is.na(ctime))) stop("NAs not allowed in the ctime.")
stopifnot(length(ctime) == length(added),
length(added) == length(removed))
if (any(duplicated(ctime))) {
ctime.u <- unique(ctime)
ctime.f <- factor(ctime, levels=as.character(ctime.u))
added <- split(added, ctime.f)
removed <- split(removed, ctime.f)
} else {
ctime.u <- ctime
}
out <- setNames(vector(mode="list", length=length(ctime.u) + 1),
c("current", as.character(ctime.u)))
out[["current"]] <- current
for (i in 2:length(out))
out[[i]] <- union(setdiff(out[[i - 1]], added[[i - 1]]),
na.omit(removed[[i - 1]]))
attr(out, "index") <- ctime.u
out
}
さらに、ctime
が上記の関数の有効な時系列クラスである場合、その出力を使用して、この関数を使用して関数 (ctime の範囲内) を使用して任意のタイムスタンプのメンバーシップを生成できますmemship_at
。
memship_at <- function (mem_ts, at) {
stopifnot(inherits(at, class(attr(mem_ts, "index"))))
just.before <- which(at > attr(mem_ts, "index"))[1]
if (just.before > 1)
mem_ts[[just.before - 1]]
else
mem_ts[[1]]
}