Home > other >  R - make the same pipeline save two objects in a list
R - make the same pipeline save two objects in a list

Time:10-09

Imagine that in the following example instead of mtcars I have some very long pipeline:

list(mtcars %>% 
         mutate(wt = wt   1),
     mtcars %>% 
         mutate(wt = wt - 1))

In order to not have to write the same long pipeline twice, and also to not have to save the intermediate object resulting from the pipeline, I was hoping to use the %T>% pipe from magrittr

mtcars %T>%
    mutate(wt = scale(wt)) %>% 
    mutate(wt = wt-1)

But that doesn't work. So in which other way can I get the same list as in the first snippet of code, without breaking the pipeline and without having to write it twice?

CodePudding user response:

To illustrate a longer pipeline yet keep the output short let us first take the first 6 rows and columns. Then use brace brackets and dot as shown.

library(dplyr)

mtcars %>%
  head(6) %>%
  select(1:6) %>%
  { list(mutate(., wt = wt   1), mutate(., wt = wt - 1)) }

giving:

[[1]]
                   mpg cyl disp  hp drat    wt
Mazda RX4         21.0   6  160 110 3.90 3.620
Mazda RX4 Wag     21.0   6  160 110 3.90 3.875
Datsun 710        22.8   4  108  93 3.85 3.320
Hornet 4 Drive    21.4   6  258 110 3.08 4.215
Hornet Sportabout 18.7   8  360 175 3.15 4.440
Valiant           18.1   6  225 105 2.76 4.460

[[2]]
                   mpg cyl disp  hp drat    wt
Mazda RX4         21.0   6  160 110 3.90 1.620
Mazda RX4 Wag     21.0   6  160 110 3.90 1.875
Datsun 710        22.8   4  108  93 3.85 1.320
Hornet 4 Drive    21.4   6  258 110 3.08 2.215
Hornet Sportabout 18.7   8  360 175 3.15 2.440
Valiant           18.1   6  225 105 2.76 2.460

This could also be done entirely in base R.

mtcars |>
  head(6) |>
  subset(select = 1:6) |>
  list(. = _) |>
  with(list(transform(., wt = wt   1), transform(., wt = wt - 1)))

CodePudding user response:

Using map2

library(purrr)
library(dplyr)
mtcars %>%
   slice_head(n = 6) %>% 
   select(1:6) %>%
   list() %>%
   map2(c(1, -1), ~ .x %>% 
           mutate(wt = wt   .y))

-output

[[1]]
                   mpg cyl disp  hp drat    wt
Mazda RX4         21.0   6  160 110 3.90 3.620
Mazda RX4 Wag     21.0   6  160 110 3.90 3.875
Datsun 710        22.8   4  108  93 3.85 3.320
Hornet 4 Drive    21.4   6  258 110 3.08 4.215
Hornet Sportabout 18.7   8  360 175 3.15 4.440
Valiant           18.1   6  225 105 2.76 4.460

[[2]]
                   mpg cyl disp  hp drat    wt
Mazda RX4         21.0   6  160 110 3.90 1.620
Mazda RX4 Wag     21.0   6  160 110 3.90 1.875
Datsun 710        22.8   4  108  93 3.85 1.320
Hornet 4 Drive    21.4   6  258 110 3.08 2.215
Hornet Sportabout 18.7   8  360 175 3.15 2.440
Valiant           18.1   6  225 105 2.76 2.460
  • Related