【问题标题】:Merge data based upon id and date in R根据 R 中的 id 和日期合并数据
【发布时间】:2020-05-11 19:00:23
【问题描述】:

我想将 2 个数据帧中的几个字段合并到一个新数据帧中。合并数据基于 ID 和日期,并且日期必须等于或介于第二个数据帧中的开始日期和结束日期之间。

以下对类似问题的回答几乎对我有用,但是如果第一个数据帧中的日期等于第二个数据帧中的开始日期,我会得到 NA 而不是匹配的颜色。非常感谢任何有关在日期落在开始日期时包含颜色的方法的帮助。

library(tidyverse)
library(lubridate)

df1 <- data.frame(ID=c(1, 2, 2, 3), 
                  actual.date=mdy('3/31/2017', '2/11/2016','4/10/2016','5/15/2015')) 

df2 <- data.frame(ID = c(1, 1, 1, 2, 3),
                  start = mdy('1/1/2000', '4/1/2011', '3/31/2017', '2/11/2016', '1/12/2012'),
                  end = mdy('3/31/2011', '6/4/2012', '04/04/2017', '3/31/2017', '2/12/2014'),
                  colour = c("blue", "purple", "blue", "red", "purple"))


df <- full_join(df1, df2, by = "ID") %>% 
  mutate(test = ifelse(actual.date <= end & actual.date > start, 
                       TRUE, 
                       FALSE)) %>% 
  filter(test) %>% 
  left_join(df1, ., by = c("ID", "actual.date")) %>% 
  select(ID, actual.date, colour)

【问题讨论】:

  • 尝试在您的mutate 通话中将actual.date &gt; start 更改为actual.date &gt;= start

标签: r date dplyr


【解决方案1】:

如果您可以向我们展示您正在寻找的输出的数据框,那将会很有用,但我认为这可能会实现您想要做的事情。我认为您不想在上面的代码中加入两次。当您执行 filter() 时,您会丢弃显示 NA 的观察结果,当您再次加入时,您会丢弃这些观察结果,因此它们显示为 NA,因为它们仅位于其中一个数据帧中。

full_join(df1, df2, by = "ID") %>% 
  filter(actual.date <= end & actual.date >= start) %>%
  select(ID, actual.date, colour)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-14
    • 2018-08-15
    • 2018-04-08
    • 1970-01-01
    • 1970-01-01
    • 2017-05-28
    • 2021-08-06
    • 1970-01-01
    相关资源
    最近更新 更多