在数据框中添加经过的时间列与日期。

huangapple go评论94阅读模式
英文:

Adding time lapsed column to data frame with date

问题

我有一个包含日期的数据框,我想在df1中添加另一列,其中包含$Date中的日期与df2$Cov.Date中的第一个条目之间的时间差,以周为单位。应该如下所示。

这是我要添加额外列的数据框df1:

  1. df1 <- data.frame (Id = c("1", "1", "2", "2"),
  2. Date = c("2005-02-05", "2005-04-05", "2005-01-15","2005-02-11")
  3. )

这是df2,我想要从中获取第一个$Date条目:

  1. df2 <- data.frame (Id = c("1", "1", "1"),
  2. Date = c("2004-12-06", "2005-01-02", "2005-01-15")
  3. )

这是我希望df1看起来的方式:

  1. df1 <- data.frame (Id = c("1", "1", "2","2"),
  2. Date = c("2005-02-05", "2005-04-05", "2005-01-15","2005-02-11"),
  3. t = c(7.14, 14.29, 2.86, 6.71)
  4. )

我可以手动添加一个包含时间的列,但我无法使它自动填充一个新列,其中包含从日期到原始日期的时间差。

英文:

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:

  1. df1 &lt;- data.frame (Id = c(&quot;1&quot;, &quot;1&quot;, &quot;2&quot;,&quot;2&quot;),
  2. Date = c(&quot;2005-02-05&quot;, &quot;2005-04-05&quot;, &quot;2005-01-15&quot;,&quot;2005-02-11&quot;)
  3. )

This is df2, I would like to pull the first $Date entry from here

  1. df2 &lt;- data.frame (Id = c(&quot;1&quot;, &quot;1&quot;, &quot;1&quot;),
  2. Date = c(&quot;2004-12-06&quot;, &quot;2005-01-02&quot;, &quot;2005-01-15&quot;)
  3. )

This is what I would like for df1 to look like:

  1. df1 &lt;- data.frame (Id = c(&quot;1&quot;, &quot;1&quot;, &quot;2&quot;,&quot;2&quot;),
  2. Date = c(&quot;2005-02-05&quot;, &quot;2005-04-05&quot;, &quot;2005-01-15&quot;,&quot;2005-02-11&quot;)
  3. t = c(7.14, 14.29, 2.86, 6.71)
  4. )

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.

  1. cbind(df1, t = as.numeric(as.Date(df1$Date) - as.Date(df2$Date[1])) / 7)
  2. Id Date t
  3. 1 1 2005-02-05 8.714286
  4. 2 1 2005-04-05 17.142857
  5. 3 2 2005-01-15 5.714286
  6. 4 2 2005-02-11 9.571429
英文:

Maybe something like this, dividing difference in days by 7.

  1. cbind(df1, t = as.numeric(as.Date(df1$Date) - as.Date(df2$Date[1])) / 7)
  2. Id Date t
  3. 1 1 2005-02-05 8.714286
  4. 2 1 2005-04-05 17.142857
  5. 3 2 2005-01-15 5.714286
  6. 4 2 2005-02-11 9.571429

huangapple
  • 本文由 发表于 2023年2月16日 02:48:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75464221.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定