r - 如何在 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)]
解决方案
as DTS
in df1
is 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
推荐阅读
- javascript - socket.io 让我感到困惑,如何通过我已有的相同端口建立连接?
- python - CIFAR-10 无意义的归一化值
- python-3.x - 不使用集合类型(如 .split())的字符串切片
- import - 有没有办法自动导入图像?
- c++ - 当我分开编译和链接时,代码不会生成
- c++ - TBB_tbb_LIBRARY_DEBUG-未找到
- xamarin.forms - 如何影响 Xamarin Forms 主题的变化,这实际上是有效的
- scala - 如何获取未来下一个特定工作日的时间戳?
- oracle - Intellij / Datagrip 是否支持存储函数?
- xamarin.android - Microsoft.ProjectOxford.Vision {“statusCode”:404,“消息”:“找不到资源”}