Julien
Julien

Reputation: 1695

Alternative to the `c()` function that works with pipes in R?

A workaround to use c() with the pipe operator is to add curly brackets

library(dplyr)

mtcars %>% {
  c(.$mpg, .$cyl)
}

But it's not pretty.

Is there alternative to the c function that works with pipes in R?

library(dplyr)

mtcars %>% 
  alternative_c(.$mpg, .$cyl) # Does such a function exist?

Upvotes: 2

Views: 166

Answers (3)

Julien
Julien

Reputation: 1695

A solution with an anonymous function

mtcars %>% 
  (\(.) c(.$mpg, .$cyl))

 [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4 10.4 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3
[25] 19.2 27.3 26.0 30.4 15.8 19.7 15.0 21.4  6.0  6.0  4.0  6.0  8.0  6.0  8.0  4.0  4.0  6.0  6.0  8.0  8.0  8.0  8.0  8.0
[49]  8.0  4.0  4.0  4.0  4.0  8.0  8.0  8.0  8.0  4.0  4.0  4.0  8.0  6.0  8.0  4.0

Upvotes: 0

lroha
lroha

Reputation: 34441

An alternative is to pipe into with():

mtcars %>% 
   with(c(mpg, cyl))

 [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4 10.4 14.7 32.4 30.4 33.9 21.5 15.5 15.2
[24] 13.3 19.2 27.3 26.0 30.4 15.8 19.7 15.0 21.4  6.0  6.0  4.0  6.0  8.0  6.0  8.0  4.0  4.0  6.0  6.0  8.0  8.0  8.0
[47]  8.0  8.0  8.0  4.0  4.0  4.0  4.0  8.0  8.0  8.0  8.0  4.0  4.0  4.0  8.0  6.0  8.0  4.0

Upvotes: 4

stefan
stefan

Reputation: 124183

Using the magrittr exposition pipe %$% you could do:

library(magrittr)

mtcars %$% c(mpg, cyl)
#>  [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4
#> [16] 10.4 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4 15.8 19.7
#> [31] 15.0 21.4  6.0  6.0  4.0  6.0  8.0  6.0  8.0  4.0  4.0  6.0  6.0  8.0  8.0
#> [46]  8.0  8.0  8.0  8.0  4.0  4.0  4.0  4.0  8.0  8.0  8.0  8.0  4.0  4.0  4.0
#> [61]  8.0  6.0  8.0  4.0

Upvotes: 5

Related Questions