以下是一些示例数据:
df <- data.frame(ID = c(1, 2, 2),
Amount = c(100, 10, 100),
Time = c(0, 0, 24),
ADDL = c(5, 0, 1),
II = c(24, 24, 24))
使用此数据框,我想生成以下行/数据框,其中ADDL是应为给定ID生成的其他行数,II项是每行新记录应占用的时间间隔。
# ID Amount Time
# 1 1 100 0
# 2 1 100 24
# 3 1 100 48
# 4 1 100 72
# 5 1 100 96
# 6 1 100 120
# 7 2 10 0
# 8 2 100 24
# 9 2 100 48
我将生成的输出数据帧将具有> 350000行,因此需要一种有效的解决方案。
#fastest option stays away from adding rows using a loop
#add rows function
addRows <- function(x){
Times <- seq(from = x$Time, to = x$Time + x$ADDL*x$II, by = x$II)
n <- length(Times)
x %>%
dplyr::slice(rep(row_number(),n)) %>%
dplyr::mutate(Time = Times)
}
df %>%
dplyr::group_by(USUBJID, TIME, ADDL) %>%
dplyr::group_split() %>%
purrr::map_dfr( ~ addRows(.))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句