英文:
Adding time lapsed column to data frame with date
问题
我有一个包含日期的数据框,我想在df1中添加另一列,其中包含$Date中的日期与df2$Cov.Date中的第一个条目之间的时间差,以周为单位。应该如下所示。
这是我要添加额外列的数据框df1:
df1 <- data.frame (Id = c("1", "1", "2", "2"),
Date = c("2005-02-05", "2005-04-05", "2005-01-15","2005-02-11")
)
这是df2,我想要从中获取第一个$Date条目:
df2 <- data.frame (Id = c("1", "1", "1"),
Date = c("2004-12-06", "2005-01-02", "2005-01-15")
)
这是我希望df1看起来的方式:
df1 <- data.frame (Id = c("1", "1", "2","2"),
Date = c("2005-02-05", "2005-04-05", "2005-01-15","2005-02-11"),
t = c(7.14, 14.29, 2.86, 6.71)
)
我可以手动添加一个包含时间的列,但我无法使它自动填充一个新列,其中包含从日期到原始日期的时间差。
英文:
I had a data frame with dates, I would like to add another column to df1 with time difference between between the date in $Date and the first entry in df2$Cov.Date, in weeks. so it should look like the following.
This is the data frame that I have, df1, that I would like to add an extra column to:
df1 <- data.frame (Id = c("1", "1", "2","2"),
Date = c("2005-02-05", "2005-04-05", "2005-01-15","2005-02-11")
)
This is df2, I would like to pull the first $Date entry from here
df2 <- data.frame (Id = c("1", "1", "1"),
Date = c("2004-12-06", "2005-01-02", "2005-01-15")
)
This is what I would like for df1 to look like:
df1 <- data.frame (Id = c("1", "1", "2","2"),
Date = c("2005-02-05", "2005-04-05", "2005-01-15","2005-02-11")
t = c(7.14, 14.29, 2.86, 6.71)
)
I can manually add a column with times, but I can't get it to automatically populate a new column with the difference in time from a date and an origin date
答案1
得分: 0
Maybe something like this, dividing difference in days by 7.
cbind(df1, t = as.numeric(as.Date(df1$Date) - as.Date(df2$Date[1])) / 7)
Id Date t
1 1 2005-02-05 8.714286
2 1 2005-04-05 17.142857
3 2 2005-01-15 5.714286
4 2 2005-02-11 9.571429
英文:
Maybe something like this, dividing difference in days by 7.
cbind(df1, t = as.numeric(as.Date(df1$Date) - as.Date(df2$Date[1])) / 7)
Id Date t
1 1 2005-02-05 8.714286
2 1 2005-04-05 17.142857
3 2 2005-01-15 5.714286
4 2 2005-02-11 9.571429
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论