Creating variable in R data frame depending on another data frame

前端 未结 4 679
后悔当初
后悔当初 2020-12-31 20:34

I am seeking help after having wasted almost a day. I have a big data frame (bdf) and a small data frame (sdf). I want to add variable z to bdf depending on the value of sdf

4条回答
  •  -上瘾入骨i
    2020-12-31 21:03

    This seems now absolutely unnecessary, but in base R

    bdf$z <- numeric(nrow(bdf))
    for(i in seq_along(bdf$z)){
      ind <- which.min(abs(bdf$tb[i] - sdf$ts))
      bdf$z[i] <- sdf$y[ind]
    }
    

    While being little clumsy, it has an advantage in clarity, which accomodates easy adaptation to dplyr

    library(dplyr)
    bdf %>% rowwise() %>% 
      mutate(z= sdf$y[which.min(abs(as.numeric(tb)-as.numeric(sdf$ts)))])
    
    #Source: local data frame [10 x 2]
    #Groups: 
    
    #                    tb    z
    #1  2013-05-19 17:11:22  0.2
    #2  2013-05-21 06:40:58  0.2
    #3  2013-05-22 20:10:34  0.2
    #4  2013-05-24 09:40:10 -0.1
    #5  2013-05-25 23:09:46 -0.1
    #6  2013-05-27 12:39:22  0.3
    #7  2013-05-29 02:08:58  0.3
    #8  2013-05-30 15:38:34  0.3
    #9  2013-06-01 05:08:10  0.3
    #10 2013-06-02 18:37:46  0.3
    

提交回复
热议问题