Skip to content

Instantly share code, notes, and snippets.

@h-a-graham
Created September 26, 2022 09:02
Show Gist options
  • Save h-a-graham/33f0009a4f9257bc5ada6de3e2af906c to your computer and use it in GitHub Desktop.
Save h-a-graham/33f0009a4f9257bc5ada6de3e2af906c to your computer and use it in GitHub Desktop.
reorder columns of a tibble based on the values of another with equal dimensions - see https://twitter.com/ProfJamesCurran/status/1574135627498475520
library(tibble)
library(purrr)

t1 <- tibble(`C1 Template` = sample(c(166:180), 10),
             `C2 Template` = sample(c(120:130), 10))

t1
#> # A tibble: 10 × 2
#>    `C1 Template` `C2 Template`
#>            <int>         <int>
#>  1           176           121
#>  2           172           128
#>  3           177           127
#>  4           178           130
#>  5           173           120
#>  6           179           125
#>  7           174           122
#>  8           169           126
#>  9           175           123
#> 10           171           129

t2 <- tibble(`k1 c slot` = sample(c(1:4), 10, replace =TRUE),
             `k2 c slot` = sample(c(1:4), 10, replace =TRUE))

t2
#> # A tibble: 10 × 2
#>    `k1 c slot` `k2 c slot`
#>          <int>       <int>
#>  1           1           3
#>  2           1           1
#>  3           1           4
#>  4           2           3
#>  5           1           1
#>  6           1           1
#>  7           3           4
#>  8           2           4
#>  9           2           4
#> 10           1           2

map2_df(t1, t2, .f = function(.x, .y){
  i <- sort(.y, index.return=TRUE)$ix
  .x[i]
})
#> # A tibble: 10 × 2
#>    `C1 Template` `C2 Template`
#>            <int>         <int>
#>  1           176           128
#>  2           172           120
#>  3           177           125
#>  4           173           129
#>  5           179           121
#>  6           171           130
#>  7           178           127
#>  8           169           122
#>  9           175           126
#> 10           174           123

Created on 2022-09-26 by the reprex package (v2.0.1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment