Home > Software engineering >  Plug values from one dataset to another that match in place
Plug values from one dataset to another that match in place

Time:06-14

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:

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

CodePudding user response:

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

CodePudding user response:

If you already have pred_mat, you could do:

pred_mat[] <- lapply(pred_mat, function(x) predictors[x])

Which results in:

pred_mat
#>   pred1 pred2
#> 1 pop15 pop75
#> 2 pop15   dgi
#> 3 pop15  ddgi
#> 4 pop75   dgi
#> 5 pop75  ddgi
#> 6   dgi  ddgi
  •  Tags:  
  • r
  • Related