I put a tibble in your tibble and here is a bug!

Hello there, consider this simple example

mytib <- tibble(var1 = c('hello world', 'all your base', 'are belong', 'to us'),
       var2 = c(1,2,3,4))

# A tibble: 4 x 2
  var1           var2
  <chr>         <dbl>
1 hello world       1
2 all your base     2
3 are belong        3
4 to us             4

I am trying to use this tibble to generate another tibble. The idea is simply to break down a long list into multiple columns. I do not understand what is wrong with this code

mytib %>% 
  tibble(one1 = .$var1[1:2],
         two1 = .$var2[1:2],
         one2 = .$var1[3:4],
         two2 = .$var2[3:4])
Error: Tibble columns must have consistent lengths, only values of length one are recycled:
* Length 2: Columns `one1`, `two1`, `one2`, `two2`
* Length 4: Column `.`
Call `rlang::last_error()` to see a backtrace

where is this column . coming from?

1 Like

When you use the pipe operator (%>%), it will always pass the input (left side) to the first parameter of the function in the right unless you use . (and . alone) to place it at a different parameter. If you use .$something, this does not change the default behavior of putting the left value into the first parameter. So you are basically calling

mytib %>% 
  tibble(., one1 = .$var1[1:2],
         two1 = .$var2[1:2],
         one2 = .$var1[3:4],
         two2 = .$var2[3:4])

The way around this using magrittr pipes, is to put a code block on the right hand side rather than an expression. If you pass a code block, the left hand side will not automatically be passed as the first parameter into any function, you must explicitly include it with .. So you can do

mytib %>% 
  {tibble(one1 = .$var1[1:2],
         two1 = .$var2[1:2],
         one2 = .$var1[3:4],
         two2 = .$var2[3:4])}

This isn't unique to tibbles at all. This is just a general rule about how pipes based on the magrittr package work in the tidyverse.

More info here: https://stackoverflow.com/questions/38717657/use-pipe-without-feeding-first-argument


thanks man! pretty clear now

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.