首页 > 解决方案 > 如何在 R 中查找

问题描述

我有两个df:

df1 <- data.frame(DTS = c(as.Date("2009-12-12"), as.Date("2012-12-12") , as.Date("2015-3-4"), 
as.Date("2018-7-9")),score= c(10,7,3,8))

df2 <- data.frame(DTS = c(as.Date("2009-12-14"), as.Date("2013-09-12") ,as.Date("2014-09-12"),  
as.Date("2015-3-4"),as.Date("2016-05-05"), as.Date("2019-12-12")))

我需要通过在 df1 中查找来找到 df2 中相关日期的分数

这可行,但远非优雅..有更好的解决方案的人吗?

df2$score <- 0

for (int_x in 1:NROW(df1)) {

   df2$score[ df2$DTS <= df1$DTS[int_x+1]  &  df2$DTS> df1$DTS [int_x] ] <- df1$score[int_x] 

 }

 df2$score[df2$DTS > df1$DTS[nrow(df1)]]   <- df1$score[NROW(df1)] 

标签: r

解决方案


as DTSin df1is sortedfindInterval可以使用。

df2$score <- df1$score[findInterval(df2$DTS, df1$DTS, left.open=TRUE)]
df2
#         DTS score
#1 2009-12-14    10
#2 2013-09-12     7
#3 2014-09-12     7
#4 2015-03-04     7
#5 2016-05-05     3
#6 2019-12-12     8

推荐阅读