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

Plug values from one dataset to another that match in place

I want to plug in values from one dataset to another when they match to replace the values in place as they are.

For example, suppose I have the following:

predictors <- c("pop15","pop75", "dgi","ddgi")
pred_mat <- combn(4, 2) %>% t() %>% data.frame() %>% setNames(., c("pred1", "pred2"))
pred_tib <- tibble(pred1=1:4, pred2=1:4, variables=predictors)
xnm <- names(pred_mat)


pred_mat[xnm] <- Map(function(x, y)pred_tib$variables[match(x,y)], pred_mat[xnm], pred_tib[xnm])

#The Map produces
$pred1
[1] "pop15" "ddpi"  NA      NA     

$pred2
[1] NA      "pop15" "pop75" "dpi"  

The expected outcome:

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

 pred1 pred2
  <chr> <chr>
1 pop15 pop75
2 pop15 dgi  
3 pop15 ddgi 
4 pop75 dgi  
5 pop75 ddgi 
6 dgi   ddgi 

>Solution :

use combn directly. Just pass in the predictors to the function.

setNames(data.frame(t(combn(predictors, 2))), c("pred1", "pred2"))

  pred1 pred2
1 pop15 pop75
2 pop15   dgi
3 pop15  ddgi
4 pop75   dgi
5 pop75  ddgi
6   dgi  ddgi
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