我有一系列的GPS点,其中包括日期和时间信息,为夜间(下午4点至上午9点)的地点.日期已经调整,所以任何超过午夜的点,都将与第一个晚上的日期相同.我在数据集中有几个不同的人,我每晚有几个读数.我试图将数据过滤到每晚最接近午夜的一个点.
我的日期和时间数据格式如下,还有一个ID列:
NightDate | timeofday | time | NightDateTime |
---|---|---|---|
2019-03-22 | 19.47 | 19:28:00 | 22/03/2019 19:28:00 |
2019-03-22 | 21.88 | 21:53:00 | 22/03/2019 21:53:00 |
2019-03-22 | 2.77 | 02:46:00 | 22/03/2019 02:46:00 |
2019-03-23 | 20.53 | 20:32:00 | 23/03/2019 20:32:00 |
2019-03-23 | 23.07 | 23:04:00 | 23/03/2019 23:04:00 |
2019-03-23 | 1.67 | 01:40:00 | 23/03/2019 01:40:00 |
2019-03-23 | 4.28 | 04:17:00 | 23/03/2019 04:17:00 |
2019-03-24 | 19.57 | 19:34:00 | 24/03/2019 19:34:00 |
2019-03-24 | 23.37 | 23:22:00 | 24/03/2019 23:22:00 |
2019-03-24 | 2.05 | 02:03:00 | 24/03/2019 02:03:00 |
2019-03-24 | 4.8 | 04:48:00 | 24/03/2019 04:48:00 |
代码是:
Night <- read.csv("night_redate.csv")
Night.filter <- Night %>%
group_by(ID, NightDate) %>%
slice(which.min(abs(timeofday - 0)))
write.csv(Night.filter, "filtered_night.csv", row.names = FALSE)
我试过的代码几乎工作了,它确实过滤了数据,一个晚上读一次,但是,它不把23.07当作接近午夜(0),只把清晨的时间当作接近0.有没有办法调整这个代码,使1.00和23.00都被认为是接近午夜的过滤?
我最初也try 使用标准的日期时间格式来解决这个问题,但代码没有正确过滤.我已经将我try 过的内容包括在下面,如果可能有用的话.列NightDateTime是日期和时间的组合.
# Remove rows with NA in 'NightDate' column and group by ID and NightDateTime
Night.edit <- Night %>%
filter(!is.na(DateTime)) %>%
group_by(ID, NightDateTime) %>%
mutate(
# Convert NightDateTime to Date
night_date = as.Date(NightDateTime),
# Create Midnight Time
midnight_time = as.POSIXct(paste(night_date, "00:00:00")),
# Calculate Time Difference
time_diff = difftime(midnight_time, NightDateTime),
# Take Absolute Value
time_diff_absolute = abs(as.numeric(time_diff))
) %>%
# Filter for the observation closest to midnight
filter(time_diff_absolute == min(time_diff_absolute))
谢谢你的帮忙!
编辑以在表和原始代码中包含更多列