'Add a (copied) value to duplicated row in R

I would like to copy a rows value in case it's duplicated in another column.

# A tibble: 10 x 3
   pat_id   Dup DD   
 1      1     1 TRUE 
 2      2     1 NA   
 3      3     3 FALSE
 4      4     4 NA   
 5      5     5 TRUE 
 6      6     5 NA   
 7      7     7 FALSE
 8      8     7 NA   
 9      9     9 FALSE
10     10    10 TRUE 

sample <- data.frame(pat_id = c(1,2,3,4,5,6,7,8,9,10), 
                     Dup = c(1,1,3,4,5,5,7,7,9,10),
                     DD = c("TRUE", "NA","FALSE", "NA", "TRUE", "NA","FALSE","NA","FALSE","TRUE"))

Column Dup has duplicates. Column DD shows TRUE/FALSE for one of these, it also has a lot of NA values. If Dup is duplicated, i would like the column DD to show the same value. If there is no duplicate and DD shows NA, it should become FALSE. I would like to get the following output.

   pat_id   Dup DD       DDx
 1      1     1 TRUE     TRUE
 2      2     1 NA       TRUE
 3      3     3 FALSE    FALSE
 4      4     4 NA       FALSE
 5      5     5 TRUE     TRUE
 6      6     5 NA       TRUE
 7      7     7 FALSE    FALSE
 8      8     7 NA       FALSE
 9      9     9 FALSE    FALSE
10     10    10 TRUE     TRUE

Ive tried it with the duplicated function, but this does not allow me to copy another columns value to the duplicated row. Thank you in advance.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source