Using the point operator in dplyr :: bind_cols

I see unexpected behavior with dplyr. I have a specific use case, but I will fix a fictitious problem to illustrate my point. Why does it work

library(dplyr)
temp <- bind_cols(mtcars %>% select(-mpg), mtcars %>% select(mpg))
head(temp)

cyl  disp  hp drat    wt  qsec vs am gear carb  mpg
6 160.0 110 3.90 2.620 16.46  0  1    4    4 21.0
6 160.0 110 3.90 2.875 17.02  0  1    4    4 21.0

But not that,

library(dplyr)
temp <- mtcars %>% bind_cols(. %>% select(-mpg), . %>% select(mpg))

Error in cbind_all(x) : Argument 2 must be length 1, not 32

Thanks for the help.

+4
source share
2 answers

You need to wrap your function using {}pipe mtcarsin a function within the following function, for example:

library(dplyr)

temp1 = mtcars %>% {bind_cols(select(., -mpg), select(., mpg))}
temp2 = bind_cols(mtcars %>% select(-mpg), mtcars %>% select(mpg))

# > identical(temp1, temp2)
# [1] TRUE
+2
source

Another solution:

myfun <- function(x) {
  bind_cols(x %>% select(-mpg), x %>% select(mpg))
}
temp <- mtcars %>% myfun
0
source

Source: https://habr.com/ru/post/1690812/


All Articles