如何在使用data.table时提取所有列?

时间:2015-05-11 12:07:08

标签: r data.table

library(data.table)

我正在尝试这样做。

wd <- structure(list(Year = c(2006L, 2006L, 2006L), day = c(361L, 361L, 
360L), hour = c(14L, 8L, 8L), mint = c(30L, 0L, 30L), valu1 = c(0.5, 
0.3, 0.4), Date = structure(c(1167229800, 1167206400, 1167121800
), class = c("POSIXct", "POSIXt"), tzone = "UTC")), .Names = c("Year", 
"day", "hour", "mint", "valu1", "Date"), row.names = c(NA, -3L
), class = "data.frame")

wg <- c("2006/12/27 14:23:59", "2006/12/27 16:47:59", "2006/12/27 19:12:00")
w <- c("0.4", "0.2", "0.5")
wf=data.frame(wg,w)
wg <- as.POSIXct(wf$wg, format = "%Y/%m/%d %T", tz = "UTC") 
WG <- data.table(start = wg, end = wg)
setkey(WG)
## Do the same for `wd` adding +/- 30 minutes 
setDT(wd)[, `:=`(start = Date - 1800L, end = Date + 1800L)]
## Run foverlaps and extract the match `valu1` column
foverlaps(wd, WG, nomatch = 0L)[, .(wdDate = Date, valu1, WGDate = start)]
                    wdDate valu1              WGDate
   1: 2006-12-27 14:30:00   0.5 2006-12-27 14:23:59

正如您在最终结果中看到的那样,valu1只提取了wd,但我还要从w中的wf中提取相应的值。

所以我想要这样的事情:

                     wdDate valu1              WGDate      w
    1: 2006-12-27 14:30:00   0.5 2006-12-27 14:23:59      0.4    

欢迎任何想法。

真实数据:

  head(wf)
       date1  date2        date3n               wg         w    whyt
1     <NA> 2003-01-01      <NA>                <NA>        NA   NA
2     <NA> 2003-01-02      <NA>                <NA>        NA   NA
3     <NA> 2003-01-03      <NA> 2003/01/03 10:30:00 0.2137352 0.34
4     <NA> 2003-01-04      <NA>                <NA>        NA   NA

遇到问题:

1 个答案:

答案 0 :(得分:5)

In my previous answer我创建了WG,因为您提供了wg作为单个向量。如果您已有一个名为wf的数据集,则不需要此整个过程。您只需正确调整wf,然后运行foverlaps即可。换句话说,忘记WG并执行以下操作

setDT(wf)[, wg := as.POSIXct(wg, format = "%Y/%m/%d %T", tz = "UTC")]
wf[, `:=`(start = wg, end = wg)]
setkey(wf, start, end)
setDT(wd)[, `:=`(start = Date - 1800L, end = Date + 1800L)]

foverlaps(wd, wf, nomatch = 0L)[, .(wdDate = Date, valu1, WGDate = start, w)]
#                 wdDate valu1              WGDate   w
# 1: 2006-12-27 14:30:00   0.5 2006-12-27 14:23:59 0.4