滚动左连接并填充左表中的所有行

问题描述 投票:0回答:1

我有两个 data.tables(以标准化形式表示同一实体的行),每个表中的行数不同,并且具有 update_at 时间戳。我想通过匹配 Updated_at 时间戳来进行滚动左连接,以便第一个 dt1 保留所有行。对于 dt1 中的所有行,只应连接并填充第二个 dt2 中最接近的值。

我见过并尝试创建一个联接的示例,其中对于不匹配的 Windows,最终表保留为 NA。但我需要 dt1 中的所有行与 dt2 中最近的记录匹配。

我从 Stack Overflow 参考文献中尝试过的代码:

library(data.table)

set.seed(42)

timestamp <- sort(rnorm(10, mean = 1, sd = 1))

dt1 <- data.table(
  id = letters[1:10],
  timestamp = timestamp,
  timestamp1 = timestamp,
  other1 = 1:10,
  other2 = 11:20
)

dt2 <- data.table(
  timestamp = timestamp[c(3, 5, 8)] + 0.1,
  timestamp2 = timestamp[c(3, 5, 8)] + 0.1,
  other3 = c("x", "y", "z"),
  other4 = c(333, 444, 555)
)

dt1[dt2,
    roll = -Inf,
    on = "timestamp", 
    # assign desired values explicitely
    `:=`(dt2_timestamp2 = i.timestamp2,
          other3 = i.other3,
         other4 = i.other4)]

收到的输出:

 id timestamp timestamp1 other1 other2 dt2_timestamp2 other3 other4
    <char>     <num>      <num>  <int>  <int>          <num> <char>  <num>
 1:      a 0.4353018  0.4353018      1     11             NA   <NA>     NA
 2:      b 0.8938755  0.8938755      2     12             NA   <NA>     NA
 3:      c 0.9053410  0.9053410      3     13             NA   <NA>     NA
 4:      d 0.9372859  0.9372859      4     14             NA   <NA>     NA
 5:      e 1.3631284  1.3631284      5     15       1.005341      x    333
 6:      f 1.4042683  1.4042683      6     16             NA   <NA>     NA
 7:      g 1.6328626  1.6328626      7     17       1.463128      y    444
 8:      h 2.3709584  2.3709584      8     18             NA   <NA>     NA
 9:      i 2.5115220  2.5115220      9     19       2.470958      z    555
10:      j 3.0184237  3.0184237     10     20             NA   <NA>     NA

所需输出:

         id timestamp timestamp1 other1 other2 dt2_timestamp2 other3 other4
    <char>     <num>      <num>  <int>  <int>          <num> <char>  <num>
 1:      a 0.4353018  0.4353018      1     11             NA   <NA>     NA
 2:      b 0.8938755  0.8938755      2     12             NA   <NA>     NA
 3:      c 0.9053410  0.9053410      3     13             NA   <NA>     NA
 4:      d 0.9372859  0.9372859      4     14             NA   <NA>     NA
 5:      e 1.3631284  1.3631284      5     15       1.005341      x    333
 6:      f 1.4042683  1.4042683      6     16       1.005341      x    333
 7:      g 1.6328626  1.6328626      7     17       1.463128      y    444
 8:      h 2.3709584  2.3709584      8     18       1.463128      y    444
 9:      i 2.5115220  2.5115220      9     19       2.470958      z    555
10:      j 3.0184237  3.0184237     10     20       2.470958      z    555
r dataframe dplyr data.table
1个回答
0
投票

您可以只使用

fill
中的
tidyr
。它会追随你的
roll

fill(dt1,names(dt1),.direction='down')
© www.soinside.com 2019 - 2024. All rights reserved.