Massimo2013
Massimo2013

Reputation: 593

Pretty-print a nested dataframe in R with purrr::map

I'd like to pretty print a nested dataframe (tibble).

Here is a minimal example

df <- tribble(~name,~data,
"first",tibble(type=c("a","b","c"),value=c(2,4,5)),
"second",tibble(type=c("a","b"),value=c(3,1)))

so that:

  name   data            
  <chr>  <list>          
1 first  <tibble [3 × 2]>
2 second <tibble [2 × 2]>

I would like to print data as follows (i.e. using the variable name as title for each data item):

 first
   type  value
 1 a         2
 2 b         4
 3 c         5

 second
   type  value
 1 a         3
 2 b         1

I am sure this must be possible using purrr::map or some similar function, but I haven't been able to do it.

Upvotes: 1

Views: 295

Answers (1)

Yuriy Saraykin
Yuriy Saraykin

Reputation: 8880

library(tidyverse)
df <- tribble(~name,~data,
              "first",tibble(type=c("a","b","c"),value=c(2,4,5)),
              "second",tibble(type=c("a","b"),value=c(3,1)))

deframe(x = df)
#> $first
#> # A tibble: 3 x 2
#>   type  value
#>   <chr> <dbl>
#> 1 a         2
#> 2 b         4
#> 3 c         5
#> 
#> $second
#> # A tibble: 2 x 2
#>   type  value
#>   <chr> <dbl>
#> 1 a         3
#> 2 b         1

Created on 2022-01-21 by the reprex package (v2.0.1)

Upvotes: 3

Related Questions