我希望合并两个向量(时间和位置)来创建一个包含每个位置所有时间的数据帧。以下是两个向量:
#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")
如何合并它们以便每个位置都有基准时间的每个日期?最后一组看起来像这样:
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
答案 0 :(得分:1)
如果我理解正确的话,这样的事情会有效:
>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
答案 1 :(得分:1)
我们可以使用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
或CJ
data.table
library(data.table)
CJ(loc=loc, base_hours=base_hours)