mutate tibble to contain col of tibbles

I have a tibble which I would like to extend with a new column containing tibbles.

Example code:

test = tribble(~a, ~b,
               1,  2,
               3,  4
mutate(test, mynewcol = tribble(~c,999))

However, this will produce:

Error: Column `mynewcol` is of unsupported class data.frame

So it seems I cannot extend tibbles via mutate with nested tibbles - but I can create them this way?

test2 = tribble(~a, ~b, ~mynewcol,
                1,  2,  tribble(~c,999),
                3,  4,  tribble(~c,999)

So what would be the correct way of adding those nested tibbles into my tibble? I know I can work with bind_cols to glue on a new tibble, but it would be nice if I could add my new values depending on other variables in the row - which is something that mutate can usually do nicely; so something like this:

mutate(test2, mynewcol = ifelse(a > 2, tribble(~xx, "xxx"),tribble(~yy, "yyy")))

Is this the kind of thing you are looking for?

#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>     filter, lag
#> The following objects are masked from 'package:base':
#>     intersect, setdiff, setequal, union
test = tribble(~a, ~b,
               1,  2,
               3,  4
test2 <- test %>% mutate(c = map(999 , as_tibble))
#> # A tibble: 2 x 3
#>       a     b c               
#>   <dbl> <dbl> <list>          
#> 1     1     2 <tibble [1 x 1]>
#> 2     3     4 <tibble [1 x 1]>

Created on 2020-05-21 by the reprex package (v0.3.0)


Do I understand correctly that I need to wrap the tibble in a list? Why?

The tibble test2 is itself a list. If you run


you will get back the object that is the first element of test2, which is a numeric vector. If you run


you get back a list rather than a numeric vector because a list can have elements which are tibbles.


Thank you, I think that has deepened my understanding of R a lot!

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