R合并包含日期和时间的数据框

时间:2014-10-25 13:13:59

标签: r

我有两个数据框。在第一个中有日期和时间(每天不总是有24个条目):

datetime
2011-01-01 00:00:00
2011-01-01 01:00:00
2011-01-01 02:00:00
2011-01-02 00:00:00
...

第二个只包含日期和值:

date          value
2011-01-01    1
2011-01-02    4
2011-01-03    3
2011-01-04    7
...

日期存储为POSIXlt类型。 我想将第二个数据框中的值附加到第一个数据框,只比较日期部分。 结果应该是这样的:

datetime               value
2011-01-01 00:00:00    1
2011-01-01 01:00:00    1
2011-01-01 02:00:00    1
2011-01-02 00:00:00    4
...

1 个答案:

答案 0 :(得分:2)

尝试

 merge(df2, transform(df1, date=as.Date(datetime)), by='date')[,(3:2)]
 #             datetime value
 #1 2011-01-01 00:00:00     1
 #2 2011-01-01 01:00:00     1
 #3 2011-01-01 02:00:00     1
 #4 2011-01-02 00:00:00     4

数据

 df1 <- structure(list(datetime = structure(list(sec = c(0, 0, 0, 0), 
 min = c(0L, 0L, 0L, 0L), hour = c(0L, 1L, 2L, 0L), mday = c(1L, 
 1L, 1L, 2L), mon = c(0L, 0L, 0L, 0L), year = c(111L, 111L, 
 111L, 111L), wday = c(6L, 6L, 6L, 0L), yday = c(0L, 0L, 0L, 
 1L), isdst = c(0L, 0L, 0L, 0L), zone = c("EST", "EST", "EST", 
"EST"), gmtoff = c(NA_integer_, NA_integer_, NA_integer_, 
NA_integer_)), .Names = c("sec", "min", "hour", "mday", "mon", 
"year", "wday", "yday", "isdst", "zone", "gmtoff"), class = c("POSIXlt", 
"POSIXt"))), .Names = "datetime", row.names = c(NA, -4L), class = "data.frame")

 df2 <- structure(list(date = structure(c(14975, 14976, 14977, 14978), class = "Date"), 
   value = c(1L, 4L, 3L, 7L)), .Names = c("date", "value"), row.names = c(NA, 
 -4L), class = "data.frame")