为每个学生ID分配多个日期

问题描述 投票:0回答:3

我有一个学生ID列表,列出1-30或student_id = c(1:30)。我现在如何使用R base包或dplyr函数为每个学生分配从01-01-2019到今天的日期。期望的将是这样的:

 Student_ID Date 
  1          01-01-2019
  1          01-02-2019
  1          01-03-2019
  1          01-04-2019 
  2          01-01-2019
  2          01-02-2019
  2          01-03-2019
  2          01-04-2019
r
3个回答
0
投票

为学生列表和日期列表创建数据框,并在没有任何键的情况下合并它们 -

s<-data.frame(student_id=c(1:30))
d<-data.frame(date=seq.Date(as.Date("2019-01-01"), Sys.Date(), by = 'days'))
merge(s,d, all=TRUE)

0
投票

您可以尝试生成一系列日期,然后根据需要重复序列。对于您的示例,假设您的data.frame被称为students

date <- seq(as.Date("01012019",format="%d%m%Y"),as.Date("04012019",format="%d%m%Y"),by=1)

students$Date <- rep(date, times = 4)

0
投票

考虑ave按组运行计数,您可以使用它来添加到开始日期2019-01-01。这可以通过Student_ID调整为任何大小分组:

df$Date <- with(df, ave(Student_ID, Student_ID, FUN=seq_along)-1 + as.Date("2019-01-01"))

df    
#   Student_ID       Date
# 1          1 2019-01-01
# 2          1 2019-01-02
# 3          1 2019-01-03
# 4          1 2019-01-04
# 5          2 2019-01-01
# 6          2 2019-01-02
# 7          2 2019-01-03
# 8          2 2019-01-04

Rextester demo

© www.soinside.com 2019 - 2024. All rights reserved.