How to find different elements of two time vectors?

眉间皱痕 提交于 2019-12-01 04:03:32

问题


Considering these two time vectors:

a<-seq(as.POSIXct("2010-01-01 05:00:00"), as.POSIXct("2010-01-02 23:55:00"), by = '5 min')
b<-seq(as.POSIXct("2010-01-01 00:00:00"), as.POSIXct("2010-01-03 23:55:00"), by = '10 min')

How to get the different elements between these two vectors? I've tried:

union(setdiff(a, b), setdiff(b, a))

But the returned values are not in time format.


回答1:


This uses only operations that preserve "POSIXct" class:

c(a[!a %in% b], b[!b %in% a])



回答2:


This will also work (using the default origin):

as.POSIXct(union(setdiff(a, b), setdiff(b, a)), origin = '1970-01-01')

#[1] "2010-01-01 05:05:00 IST" "2010-01-01 05:15:00 IST" "2010-01-01 05:25:00 IST" "2010-01-01 05:35:00 IST" "2010-01-01 05:45:00 IST"
#[6] "2010-01-01 05:55:00 IST" "2010-01-01 06:05:00 IST" "2010-01-01 06:15:00 IST" "2010-01-01 06:25:00 IST" "2010-01-01 06:35:00 IST"

# this checks a U b = (a - b) U (b - a) U (a /\ b) for PoSIxct objects, should evaluate to true
all(sort(as.POSIXct(union(union(setdiff(a, b), setdiff(b, a)), intersect(a, b)), origin = '1970-01-01')) == sort(as.POSIXct(union(a, b), origin = '1970-01-01')))
# TRUE


来源:https://stackoverflow.com/questions/41311678/how-to-find-different-elements-of-two-time-vectors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!