R - Assign column value based on closest match in second data frame

后端 未结 2 1089
暖寄归人
暖寄归人 2021-01-05 17:03

I have two data frames, logger and df (times are numeric):

logger <- data.frame(
time = c(1280248354:1280248413),
temp = runif(60,min=18,max=24.5)
)

df &         


        
2条回答
  •  花落未央
    2021-01-05 17:25

    You could use the data.table library. This will also help with being more efficient with large data size -

    library(data.table)
    
    logger <- data.frame(
      time = c(1280248354:1280248413),
      temp = runif(60,min=18,max=24.5)
    )
    
    df <- data.frame(
      obs = c(1:10),
      time = runif(10,min=1280248354,max=1280248413)
    )
    
    logger <- data.table(logger)
    df <- data.table(df)
    
    setkey(df,time)
    setkey(logger,time)
    
    df2 <- logger[df, roll = "nearest"]
    

    Output -

    > df2
              time     temp obs
     1: 1280248356 22.81437   7
     2: 1280248360 24.08711  10
     3: 1280248366 22.31738   2
     4: 1280248367 18.61222   5
     5: 1280248388 19.46300   4
     6: 1280248393 18.26535   6
     7: 1280248400 20.61901   9
     8: 1280248402 21.92584   1
     9: 1280248410 19.36526   8
    10: 1280248410 19.36526   3
    

提交回复
热议问题