【问题标题】:Date counting in RR中的日期计数
【发布时间】:2017-09-06 23:27:17
【问题描述】:

我有一个df,变量命名如下

id indexDate eventDate1 eventDate2 V1 V2 V3 ....... V365

对于日期范围 (eventDate1 - indexDate)(eventDate2 - indexDate),我想在 V1 to V365 列中标记发生的日期。

每个V 代表indexDate 之后的天数。

例如:

如果:
indexDate is 1/1/2017
eventDate1 is 1/3/2017 (= Day 2)
eventDate2 is 1/5/2017 (= Day 4),

然后:

V2-V4 将被赋值为 1,其余的 V~ 为 0。

如果有更好的方法,请随时告诉我!

谢谢。

【问题讨论】:

  • 为了更好的东西,它需要与其他东西进行比较。你能展示你尝试过的东西吗?你能提供一个可重现的数据集供人们尝试吗?
  • 也许我不清楚,但我目前没有解决方案。

标签: r date dplyr counting


【解决方案1】:

这行得通-

library(dplyr)
library(tidyr)

# Make fake data
dates <- data.frame(id = 1:10,
                    indexDate = rep(as.Date("17/01/01"), 10), 
                    eventDate1 = as.Date(paste0("17/01/", 1:10)),
                    eventDate2 = as.Date(paste0("17/01/", 16:25)))

# Step through this to understand what's going on
dates[rep(row.names(dates), 365), ] %>% 
  arrange(id) %>% 
  mutate(Day = rep(1:365, nrow(dates)),
         Flag = ifelse(Day <= as.numeric(eventDate2 - indexDate) & 
                         Day > as.numeric(eventDate1 - indexDate), 1, 0)) %>%
  # move to long format
  spread(Day, Flag)

我尝试添加paste0("V", Day),但传播结果是无序的。使用此列约定,您可以使用反引号 ` 引用各个列。

dates %>% select(`1`, `2`, `3`)

【讨论】:

  • 感谢丹的帮助!
猜你喜欢
  • 2021-05-06
  • 2014-12-07
  • 1970-01-01
  • 1970-01-01
  • 2021-11-10
  • 1970-01-01
  • 2020-05-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多