Home > front end >  Replicate %>% behavior with |>
Replicate %>% behavior with |>

Time:12-01

I have a data:

set.seed(123)
df_2 <- data.frame(x = replicate(n = 10, expr = sample(x = 1:4, size = 10, replace = TRUE)))

I tried replicate the behavior of mutate and arrange with |> pipe. Something like (it's wrong):

df_2 |> 
  cbind(lapply(X = (`[`)(c("x.1", "x.2")), FUN = function(x) {
    sum(x)
  }) |> 
    sort(x = c("x.1", "x.4")))

Error in sum(x) : invalid 'type' (character) of argument

Expected result:

library(tidyverse)

df_2 %>% 
  mutate(.data = ., across(.cols = c("x.1", "x.4"), .fns = ~ sum(.), .names = "r{col}")) %>% 
  arrange(x.1, x.4)

   x.1 x.2 x.3 x.4 x.5 x.6 x.7 x.8 x.9 x.10 rx.1 rx.4
1    1   3   3   2   1   4   2   4   1    4   25   26
2    1   2   2   2   2   3   3   3   2    3   25   26
3    1   4   1   4   4   3   3   2   4    4   25   26
4    2   4   3   2   2   3   2   4   3    3   25   26
5    2   2   2   4   2   3   4   3   2    3   25   26
6    3   4   3   2   3   3   3   4   1    4   25   26
7    3   3   1   2   4   1   2   4   3    1   25   26
8    4   1   3   2   2   1   3   1   3    4   25   26
9    4   2   4   3   4   2   2   4   1    1   25   26
10   4   2   1   3   2   3   1   2   2    4   25   26

CodePudding user response:

To use the left hand side more than once on the right hand side define a function on the right hand side when using |> . We have defined the functions inline but could define them prior to the pipeline, if desired.

df_2 |>
  (\(x) cbind(x, r = lapply(x[c("x.1", "x.4")], sum)))() |>
  (\(x) x[order(x$x.1, x$x.4), ])()

giving:

   x.1 x.2 x.3 x.4 x.5 x.6 x.7 x.8 x.9 x.10 r.x.1 r.x.4
10   1   3   2   4   3   1   1   4   1    3    24    24
6    2   3   3   1   1   4   2   2   2    1    24    24
7    2   4   4   3   1   2   1   4   3    1    24    24
8    2   1   2   3   2   1   1   3   3    2    24    24
4    2   1   1   4   1   1   3   1   4    2    24    24
1    3   4   1   1   3   4   1   2   2    2    24    24
9    3   3   3   1   3   2   3   4   4    3    24    24
2    3   2   4   2   4   1   4   1   2    2    24    24
5    3   2   1   2   3   3   1   3   2    4    24    24
3    3   2   1   3   2   3   4   3   3    1    24    24

If the main purpose of this is to use a pipeline without any packages another approach which is pipeline-like is the Bizarro pipe (which is not actually a pipe but looks like one).

df_2 ->.;
  cbind(., r = lapply(.[c("x.1", "x.4")], sum)) ->.;
  .[order(.$x.1, .$x.4), ]
  •  Tags:  
  • r
  • Related