Reputation: 3726
I have two data frames. In the first one there are dates and times (there are not always present 24 entries for each day):
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
...
The second one contains only dates and a value:
date value
2011-01-01 1
2011-01-02 4
2011-01-03 3
2011-01-04 7
...
Dates are stored as POSIXlt types. I want to attach the value from the second data frame to the first one, comparing only the date part. The result should be this:
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
...
Upvotes: 0
Views: 68
Reputation: 886948
Try
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")
Upvotes: 2