Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

fill values based on value for matched IDs

I am looking for a data.table solution to a simply problem. I have data like so

library(data.table)
data <- data.table(
  id = seq(1:20),
  match_id = c( rep(1,5), rep(2,5), rep(3,5), rep(4,5)  ),
  exp = c( 1, rep(0,4), 1 , rep(0,4), 1 , rep(0,4), 1 , rep(0,4) )
)
data[, var := ifelse(exp==1, runif(1,min=0,max=100), 0), by = id]

I want, for each unique match_id where exp==0 to fill var based on the value of var for exp==1. Data to end up with:

data_want <- data.table(
  id = seq(1:20),
  match_id = c( rep(1,5), rep(2,5), rep(3,5), rep(4,5)  ),
  exp = c( 1, rep(0,4), 1 , rep(0,4), 1 , rep(0,4), 1 , rep(0,4) ),
  var = c(rep(data[1]$var,5), rep(data[6]$var,5), rep(data[11]$var,5), rep(data[16]$var,5))
)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

data[, var:=var[which(exp==1)], by=match_id]

       id match_id   exp       var
    <int>    <num> <num>     <num>
 1:     1        1     1 75.342705
 2:     2        1     0 75.342705
 3:     3        1     0 75.342705
 4:     4        1     0 75.342705
 5:     5        1     0 75.342705
 6:     6        2     1 81.822968
 7:     7        2     0 81.822968
 8:     8        2     0 81.822968
 9:     9        2     0 81.822968
10:    10        2     0 81.822968
11:    11        3     1  3.309884
12:    12        3     0  3.309884
13:    13        3     0  3.309884
14:    14        3     0  3.309884
15:    15        3     0  3.309884
16:    16        4     1  2.047301
17:    17        4     0  2.047301
18:    18        4     0  2.047301
19:    19        4     0  2.047301
20:    20        4     0  2.047301
       id match_id   exp       var
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading