主题
我有两个(简化的)数据集:
目标是将第二个数据集的温度作为新变量添加到第一个数据集中,其中变量date.time对应于日期变量。
我尝试使用setkey()和roll =“nearest”的data.table解决方案,根据:R – How to join two data frames by nearest time-date?
不幸的是,合并的温度始终与整个合并数据集的值相同。
简化示例
以下是说明我的问题和解决方案尝试的示例代码:
设置随机种子
set.seed(10)
生成两个数据集
observations <- data.frame(date.time = seq(from=ymd_hms("2017-02-01 00:00:00"), length.out=500, by=60*60), some.value = runif(500,0.0,1.0))
daily.temperature <- data.frame(date = seq(from=as.Date("2017-02-01"), length.out = 10, by=1), temperature = runif(10,10,40))
使用data.tables和roll =“最近”
的解决方案尝试# converting dataframes to datatables
library(data.table)
observations <- as.data.table(observations)
daily.temperature <- as.data.table(daily.temperature)
# setting the keys of the two datasets
setkey(observations,date.time)
setkey(daily.temperature,date)
# Combinding the datasets
combined <- daily.temperature[observations, roll = "nearest" ]
combined
请注意,无论日期如何,组合数据集中的温度变量始终相同。
注意未简化(真实)问题的注释:
答案 0 :(得分:0)
你想要这样的东西吗?
set.seed(10)
library(dplyr)
observations <- data.frame(date.time = seq(from=ymd_hms("2017-02-01 00:00:00"), length.out=500, by=60*60), some.value = runif(500,0.0,1.0))
daily.temperature <- data.frame(date = seq(from=as.Date("2017-02-01"), length.out = 10, by=1), temperature = runif(10,10,40))
observations$date<-as.Date(observations$date.time)
combined<-left_join(observations,daily.temperature,by="date")
> head(combined)
date.time some.value date temperature
1 2017-02-01 00:00:00 0.8561467 2017-02-01 38.64702
2 2017-02-01 01:00:00 0.7820957 2017-02-01 38.64702
3 2017-02-01 02:00:00 0.2443390 2017-02-01 38.64702
4 2017-02-01 03:00:00 0.3138552 2017-02-01 38.64702
5 2017-02-01 04:00:00 0.1284753 2017-02-01 38.64702
6 2017-02-01 05:00:00 0.9299472 2017-02-01 38.64702