Search code examples
rtidyversepurrrtibble

R Why does a list of Tibble's display as a list of Tibble's and a vector of Tibble's displays as a individual columns of the Tibble?


R Why does a list of Tibble's display as a list of Tibble's and a vector of Tibble's displays as a individual columns of the Tibble?

library(tidyverse)

t1 <- tibble(num = 1:7, ll = letters[1:7])

t2 <- tibble(num = 8:14, ll = letters[8:14])

t3 <- tibble(num = 15:21, ll = letters[15:21])

vecs <- c(t1, t2, t3)

lis <- list(t1, t2, t3)

vecs %>% str
#> List of 6
#>  $ num: int [1:7] 1 2 3 4 5 6 7
#>  $ ll : chr [1:7] "a" "b" "c" "d" ...
#>  $ num: int [1:7] 8 9 10 11 12 13 14
#>  $ ll : chr [1:7] "h" "i" "j" "k" ...
#>  $ num: int [1:7] 15 16 17 18 19 20 21
#>  $ ll : chr [1:7] "o" "p" "q" "r" ...

lis %>% str
#> List of 3
#>  $ : tibble [7 × 2] (S3: tbl_df/tbl/data.frame)
#>   ..$ num: int [1:7] 1 2 3 4 5 6 7
#>   ..$ ll : chr [1:7] "a" "b" "c" "d" ...
#>  $ : tibble [7 × 2] (S3: tbl_df/tbl/data.frame)
#>   ..$ num: int [1:7] 8 9 10 11 12 13 14
#>   ..$ ll : chr [1:7] "h" "i" "j" "k" ...
#>  $ : tibble [7 × 2] (S3: tbl_df/tbl/data.frame)
#>   ..$ num: int [1:7] 15 16 17 18 19 20 21
#>   ..$ ll : chr [1:7] "o" "p" "q" "r" ...

Created on 2023-03-22 with reprex v2.0.2

I was expecting the list and vectors to be treated the same.


Solution

  • c just removes the tibble/data.frame classes and returns the underlying list structure on which it was built. By default, the recursive option is FALSE, thus according to the documenation ?"c"

    If recursive = TRUE, the function recursively descends through lists (and pairlists) combining all their elements into a vector.

    Thus, we get a list of vectors and not just a single vector

    > c(t1)
    $num
    [1] 1 2 3 4 5 6 7
    
    $ll
    [1] "a" "b" "c" "d" "e" "f" "g"
    

    where as list wraps the structure inside a list

    > list(t1)
    [[1]]
    # A tibble: 7 × 2
        num ll   
      <int> <chr>
    1     1 a    
    2     2 b    
    3     3 c    
    4     4 d    
    5     5 e    
    6     6 f    
    7     7 g