我有一个表格的数据集:
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), ]
但是,我想在日期上创建一个序列而不是复制,并让频率告诉我这个的长度。即对于第 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)
}
就我个人而言,我不喜欢我需要从列表中隐藏日期并根据此转换提供来源的方式,以防将来发生变化,但我非常感谢这些想法和帮助