我有两个数据帧,第一个跨越3个月,每2.5分钟记录一次深度。
shark depth temperature datetime date location
A 49.5 26.2 20/03/2018 08:00 20/03/2018 SS04
A 49.5 25.3 20/03/2018 08:02 20/03/2018 SS04
A 53.0 24.2 20/03/2018 08:04 20/03/2018 SS04
A 39.5 26.5 20/03/2018 08:32 20/03/2018 Absent
A 43.0 26.2 21/03/2018 09:10 21/03/2018 Absent
A 44.5 26.5 21/03/2018 10:18 21/03/2018 SS04我有第二个数据帧,列出了这三个月的潮汐状态。
date time depth tide_state datetime
18/03/2018 02:33 2.09 High 20/03/2018 02:33
18/03/2018 08:39 0.45 Low 20/03/2018 08:39
18/03/2018 14:47 2.14 High 20/03/2018 14:47
18/03/2018 20:54 0.41 Low 20/03/2018 20:54
19/03/2018 03:01 2.13 High 21/03/2019 03:01
19/03/2018 09:09 0.41 Low 21/03/2019 09:09我想创建一个新的数据集,它根据每个数据集中的datetime列,为第一个数据集上的所有值插入潮汐状态。例如,如果低潮在08:39,高潮在14:47,我希望df1中每个大于08:39但小于14:47的值都记录为“低”,并且在此之后但在下一个低潮之前的值为“高”。
由于潮汐的时间每天变化三到四次,我不太确定如何将它们合并到R中。我不确定是否有一种简单的方法可以使用data.table来做到这一点?
我将每个数据帧中的两个datetime列都设置为POSIXct值。
理想情况下,我希望生成一个数据帧形式的表,如下所示:
shark depth temperature datetime date location tide_state
A 49.5 26.2 20/03/2018 08:00 20/03/2018 SS04 High
A 49.5 25.3 20/03/2018 08:02 20/03/2018 SS04 High
A 53.0 24.2 20/03/2018 08:04 20/03/2018 SS04 High
A 39.5 26.5 20/03/2018 08:32 20/03/2018 Absent Low
A 43.0 26.2 20/03/2018 09:10 21/03/2018 Absent Low
A 44.5 26.5 20/03/2018 10:18 21/03/2018 SS04 Low发布于 2019-06-27 02:32:24
如果数据更大或者连接更复杂,我建议使用SQL或data.table进行非相等连接。对于这种大小的数据,您只需要“来自table2的最新值”,我们可以在dplyr中使用一种更简单的方法,我希望它会很快。
# First some housekeeping. It will be useful to have datetimes for sorting
library(dplyr)
df1 <- df1 %>% mutate(datetime = lubridate::dmy_hm(datetime))
tides <- tides %>% mutate(datetime = lubridate::dmy_hm(datetime))
# I collate the two tables, sort by datetime, fill in the tide info, and then remove the tide rows.
df1 %>%
bind_rows(tides %>%
select(datetime, tide_state, tide_depth = depth) %>%
mutate(tide_row_to_cut = TRUE)) %>% # EDIT
arrange(datetime) %>%
tidyr::fill(tide_depth, tide_state) %>%
filter(!tide_row_to_cut) %>% # EDIT
select(-tide_row_to_cut) # EDIT编辑:以前的版本在Temperature中使用NA来裁剪tide行不适用于原始poster,所以我在潮汐数据中添加了一个名为tide_row_to_cut的显式列,以使该修剪步骤更加健壮。
shark depth temperature datetime date location tide_state tide_depth
1 A 49.5 26.2 2018-03-20 08:00:00 20/03/2018 SS04 High 2.09
2 A 49.5 25.3 2018-03-20 08:02:00 20/03/2018 SS04 High 2.09
3 A 53.0 24.2 2018-03-20 08:04:00 20/03/2018 SS04 High 2.09
4 A 39.5 26.5 2018-03-20 08:32:00 20/03/2018 Absent High 2.09
5 A 43.0 26.2 2018-03-21 09:10:00 21/03/2018 Absent Low 0.41
6 A 44.5 26.5 2018-03-21 10:18:00 21/03/2018 SS04 Low 0.41我相信这遵循了说明,但它与请求的输出略有不同,因为低潮发生在08:39,即08:32读数之后的几分钟。那时潮水会很低,但还不会达到最低。你可能需要寻找“最接近”的潮汐。要做到这一点,一种方法是将潮汐的时间移回前一次潮汐的一半,或固定数量(例如2小时?)。
https://stackoverflow.com/questions/56778826
复制相似问题