How to display the elements of a list within a tibble?

1.5k views Asked by At

I have the following tibble:

    data_frame(type = list( c('1','2', 'text'), c(1L ,2L), c(1.5, 2.1), c(TRUE, FALSE))) %>% 
      mutate(typeof=unlist(map(type, typeof)), 
mode= unlist(map(type, mode)), 
class= unlist(map(type, class)))
# A tibble: 4 x 4
       type    typeof      mode     class
     <list>     <chr>     <chr>     <chr>
1 <chr [3]> character character character
2 <int [2]>   integer   numeric   integer
3 <dbl [2]>    double   numeric   numeric
4 <lgl [2]>   logical   logical   logical

and I want to add a column with the content of the column type, like:

# A tibble: 4 x 4
       type    typeof      mode     class  vector
     <list>     <chr>     <chr>     <chr>   <chr>
1 <chr [3]> character character character   c('1','2', 'text')
2 <int [2]>   integer   numeric   integer   c(1L ,2L)
3 <dbl [2]>    double   numeric   numeric   c(1.5, 2.1)
4 <lgl [2]>   logical   logical   logical   c(TRUE, FALSE)

I tried unlist(map(type, quote)) but it gives:

# A tibble: 4 x 5
       type    typeof      mode     class   vector
     <list>     <chr>     <chr>     <chr>   <list>
1 <chr [3]> character character character <symbol>
2 <int [2]>   integer   numeric   integer <symbol>
3 <dbl [2]>    double   numeric   numeric <symbol>
4 <lgl [2]>   logical   logical   logical <symbol>

Not even sure what <symbol> is either...

1

There are 1 answers

0
www On

First of all, if your are using the purrr package, unlist is probably not necessary when creating the example data frame. We can use map_chr to get the same output.

library(tidyverse)
dt <- data_frame(type = list(c('1','2', 'text'), c(1L ,2L), c(1.5, 2.1), c(TRUE, FALSE))) %>% 
  mutate(typeof = map_chr(type, typeof), 
         mode = map_chr(type, mode), 
         class = map_chr(type, class))

As for your desired output, I think we can use map_chr with toString to create a character string with all the contents in a list. Although it is still a little different than the output you want, I think it serves the demonstration purpose.

dt2 <- dt %>% mutate(vector = map_chr(type, toString))

dt2
# A tibble: 4 x 5
       type    typeof      mode     class      vector
     <list>     <chr>     <chr>     <chr>       <chr>
1 <chr [3]> character character character  1, 2, text
2 <int [2]>   integer   numeric   integer        1, 2
3 <dbl [2]>    double   numeric   numeric    1.5, 2.1
4 <lgl [2]>   logical   logical   logical TRUE, FALSE