使用POSIXct格式化两个不同的数据帧以进行left_join()-ing

时间:2019-03-28 12:29:14

标签: r posixct

我对R很陌生,我想left_join()以下两个数据集:

> head(datagps)
   Date & Time [Local]  Latitude Longitude            DateTime    meters
1:    18/06/2018 03:16 -2.434613  34.85372 2018-06-18 03:16:00 12.036834
2:    18/06/2018 03:20 -2.434511  34.85376 2018-06-18 03:20:00 18.738134
3:    18/06/2018 03:24 -2.434503  34.85393 2018-06-18 03:24:00 26.781879
4:    18/06/2018 03:28 -2.434719  34.85382 2018-06-18 03:28:00  8.341659
5:    18/06/2018 03:33 -2.434718  34.85375 2018-06-18 03:33:00 11.332758
6:    18/06/2018 03:36 -2.434817  34.85377 2018-06-18 03:36:00 15.736907
> head(datasensorraw)
# A tibble: 6 x 4
  TimeGroup               x     y     z
  <dttm>              <int> <int> <dbl>
1 2018-06-09 04:48:00     3     5  5.83
2 2018-06-09 04:52:00     0     0  0   
3 2018-06-09 04:56:00    29    31 42.8 
4 2018-06-09 05:00:00    10     5 11.2 
5 2018-06-09 05:04:00     2    10 10.2 
6 2018-06-09 05:08:00     0     0  0 

但是,其中之一采用POSIXct格式,而另一种则不是,因为我尝试了以下代码:

> dataresults<-left_join(datagps, datasensorraw, by = c("Date & Time [Local]" = "TimeGroup"))
Error in left_join_impl(x, y, by_x, by_y, aux_x, aux_y, na_matches) : 
  cannot join a POSIXct object with an object that is not a POSIXct object

如何知道二者之一是POSIXct格式,又如何格式化另一个以便left_join()成功?我看过其他示例,但是我不明白何时需要使用-/

感谢任何输入!

1 个答案:

答案 0 :(得分:1)

这是因为第一数据集列Date & Time [Local]不是'DateTime'类。转换为POSIXct可以解决问题

library(dplyr)
datagps %>% 
      mutate(`Date & Time [Local]` = as.POSIXct(`Date & Time [Local]`, 
           format = "%d/%m/%Y %H:%M")) %>%
      left_join(datasensorraw, by = c("Date & Time [Local]" = "TimeGroup"))