merge two vectors to create duplicates for one group

77 Views Asked by At

I'm looking to merge two vectors (time and location) to create a data frame that has all the times for every location. Below are the two vectors:

#Here are the hours
    base_hours = seq(
      from=as.POSIXct("2015-1-1 0:00", tz="America/New_York"),
      to=as.POSIXct("2015-1-3 23:00", tz="America/New_York"),
      by="hour"
    )

 #hypothetical locations
    loc = c("woodside", "corona", "jackson heights", "flushing")

How do I merge them so that every location has every date in base hours? the final set would look something like this:

loc              hours
woodside          2015-01-01 00:00:00 EST
woodside          2015-01-01 01:00:00 EST
woodside          2015-01-01 02:00:00 EST
corona            2015-01-01 00:00:00 EST
corona            2015-01-01 01:00:00 EST
corona            2015-01-01 02:00:00 EST
2

There are 2 best solutions below

1
On BEST ANSWER

If I am understanding this correctly, something like this would work:

>final <- merge(loc, base_hours)
>colnames(final) <- c("loc","hours")
>final
            *loc               hours
1          woodside 2015-01-01 00:00:00
2            corona 2015-01-01 00:00:00
3   jackson heights 2015-01-01 00:00:00
4          flushing 2015-01-01 00:00:00
5          woodside 2015-01-01 01:00:00
6            corona 2015-01-01 01:00:00
7   jackson heights 2015-01-01 01:00:00
8          flushing 2015-01-01 01:00:00
9          woodside 2015-01-01 02:00:00
10           corona 2015-01-01 02:00:00
11  jackson heights 2015-01-01 02:00:00
0
On

We can use expand.grid

res <- expand.grid(loc = loc, base_hours = base_hours)
head(res)
#              loc          base_hours
#1        woodside 2015-01-01 00:00:00
#2          corona 2015-01-01 00:00:00
#3 jackson heights 2015-01-01 00:00:00
#4        flushing 2015-01-01 00:00:00
#5        woodside 2015-01-01 01:00:00
#6          corona 2015-01-01 01:00:00

Or with CJ from data.table

library(data.table)
CJ(loc=loc, base_hours=base_hours)