Search code examples
rpurrr

Name new variables with purrr::map()


I am trying to learn some basic purrr. Take this toy example - how do I essentially append "rank" to the current variable name as it's created using map_df?

library(tidyverse)
# generate some random data
dat <- tibble(
  x_1 = runif(10),
  x_2 = runif(10),
  x_3 = runif(10)
)
# find the ranks
dat <-  cbind(dat, dat |> map_df(rank))

Currently the following is produced:

> dat
          x_1        x_2       x_3 x_1 x_2 x_3
1  0.37593751 0.20597008 0.4826491   6   3   4
2  0.01805845 0.05432019 0.6732073   1   1   7
3  0.39243407 0.47535664 0.9920948   7   7  10
4  0.06361097 0.21624621 0.4309171   2   4   3
5  0.53391717 0.28778664 0.9323643   9   6   9
6  0.24612385 0.83270359 0.2719036   4  10   1
7  0.47170853 0.26261303 0.3418129   8   5   2
8  0.33821497 0.57270648 0.7606502   5   9   8
9  0.85717819 0.48097921 0.4848689  10   8   5
10 0.11503862 0.07063651 0.6391102   3   2   6

Solution

  • In general, this wouldn't be done with purrr, you'd just do it directly with mutate and across.

    > dat |> 
    +   mutate(
    +     across(
    +       .cols = everything(),
    +       .fns = ~rank(.x),
    +       .names = "{.col}_rank"
    +     )
    +   )
    # A tibble: 10 × 6
          x_1   x_2     x_3 x_1_rank x_2_rank x_3_rank
        <dbl> <dbl>   <dbl>    <dbl>    <dbl>    <dbl>
     1 0.595  0.951 0.00114        9       10        1
     2 0.103  0.232 0.0796         2        1        2
     3 0.420  0.546 0.129          8        4        4
     4 0.302  0.774 0.995          7        8       10
     5 0.713  0.754 0.944         10        7        9
     6 0.182  0.483 0.908          5        3        8
     7 0.297  0.744 0.122          6        6        3
     8 0.150  0.640 0.804          4        5        6
     9 0.0747 0.820 0.199          1        9        5
    10 0.145  0.470 0.849          3        2        7