次の形式のデータセットがあります。
df <- data.frame(var1 = c("1976-07-04" , "1980-07-04" , "1984-07-04" ),
var2 = c('d', 'e', 'f'),
freq = 1:3)
次の方法でインデックスを作成することにより、この data.frame を非常に迅速に拡張できます。
df.expanded <- df[rep(seq_len(nrow(df)), df$freq), ]
ただし、日付の複製ではなくシーケンスを作成し、freq にこれの長さを教えてもらいたいです。つまり、行 3 の場合、展開された data.frame を次のように埋めるエントリを作成できます。
seq(as.Date('1984-7-4'), by = 'days', length = 3)
誰でもこれを行うための高速な方法を提案できますか? 私の方法は、これを行うためにさまざまなlapply関数を使用することです
Gavin Simpson の回答と以前のアイデアを組み合わせてソリューションを使用しました。
ExtendedSeq <- function(df, freq.col, date.col, period = 'month') {
#' An R function to take a data fame that has a frequency col and explode the
#' the dataframe to have that number of rows and based on a sequence.
#' Args:
#' df: A data.frame to be exploded.
#' freq.col: A column variable indicating the number of replicates in the
#' new dataset to make.
#' date.col: A column variable indicating the name or position of the date
#' variable.
#' period: The periodicity to apply to the date.
# Replicate expanded data form
df.expanded <- df[rep(seq_len(nrow(df)), df[[freq.col]]), ]
DateExpand <- function(row, df.ex, freq, col.date, period) {
#' An inner functions to explode a data set and build out days sequence
#' Args:
#' row: Each row of a data set
#' df.ex: A data.frame, to expand
#' freq: Column indicating the number of replicates to make.
#' date: Column indicating the date variable
#' Output:
#' An exploded data set based on a sequence expansion of a date.
times <- df.ex[row, freq]
# period <- can edit in the future if row / data driven.
date.ex <- seq(df.ex[row, col.date], by = "days", length = times)
return(date.ex)
}
dates <- lapply(seq_len(nrow(df)),
FUN = DateExpand,
df.ex = df,
freq = freq.col,
col.date = date.col,
period = period)
df.expanded[[date.col]] <- as.Date(unlist(dates), origin = '1970-01-01')
row.names(df.expanded) <- NULL
return(df.expanded)
}
個人的には、リストから日付を元に戻して、将来これが変更された場合に備えて、この変換に基づいて起源を提供する必要がある方法は好きではありませんが、アイデアと助けに本当に感謝しています