【问题标题】:max(DF1$EFFDT) <= DF2$EFFDT [duplicate]最大(DF1$EFFDT)<= DF2$EFFDT [重复]
【发布时间】:2021-11-23 11:28:23
【问题描述】:

我有两个数据框,DF1 包含数据的每月数据快照,而 DF2 具有特定日期,我希望能够仅从 DF1 wrt DF2 数据中检索最接近 maxdate (

DF1

Account Date
A1000001 1-JAN-2021
A1000002 1-FEB-2021
A1000003 1-MAR-2021
A1000004 1-APR-2021

DF2

Date
15-MAR-2021

预期输出:

Account Date
A1000003 1-MAR-2021

【问题讨论】:

    标签: r dataframe date


    【解决方案1】:

    将日期更改为实际日期类并使用sapply,您可能会在df1 中找到与df2 中每个日期最接近的日期。

    df1$Date <- as.Date(df1$Date, '%d-%b-%Y')
    df2$Date <- as.Date(df2$Date, '%d-%b-%Y')
    result <- df1[sapply(df2$Date, function(x) which.min(abs(df1$Date - x))), ]
    result
    
    #   Account       Date
    #3 A1000003 2021-03-01
    

    数据

    如果您在reproducible format 中提供数据会更容易提供帮助

    df1 <- structure(list(Account = c("A1000001", "A1000002", "A1000003", 
    "A1000004"), Date = c("1-JAN-2021", "1-FEB-2021", "1-MAR-2021", 
    "1-APR-2021")), row.names = c(NA, -4L), class = "data.frame")
    
    df2 <- structure(list(Date = "15-MAR-2021"), row.names = c(NA, -1L), 
    class = "data.frame")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-26
      • 2021-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-21
      • 1970-01-01
      相关资源
      最近更新 更多