Home > Software engineering >  Alternative to the c() function that works with pipes in R?
Alternative to the c() function that works with pipes in R?

Time:09-27

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?

CodePudding user response:

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

CodePudding user response:

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
  • Related