convert weird list to tibble

Hello there!

I cant believe I am struggling with this simple question. Here is my list.


list('col1' = 2, 'col2' = NULL, col3 = 'wow') 
$col1
[1] 2

$col2
NULL

$col3
[1] "wow"

I am trying to convert it to a one-row tibble where the columns are col1, col2 and col3.

Because of the NULL, as_tibble() does not work. And enframe() does not use the column names (they are stored as variables...). I am lost here.


> list('col1' = 2, 'col2' = NULL, col3 = 'wow') %>% as_tibble(validate = FALSE)
Error: All columns in a tibble must be 1d or 2d objects:
* Column `col2` is NULL
Call `rlang::last_error()` to see a backtrace


> list('col1' = 2, 'col2' = NULL, col3 = 'wow') %>% enframe()
# A tibble: 3 x 2
  name  value    
  <chr> <list>   
1 col1  <dbl [1]>
2 col2  <NULL>   
3 col3  <chr [1]>

Any ideas?

Thanks!

I am not sure you can build a data.frame or a tibble with a NULL cell. It would mean a column with 0 row. So you can't create it near a column with 1 row.

data.frame(a = 1, b = NULL)
#> Error in data.frame(a = 1, b = NULL): arguments imply different row number : 1, 0
tibble::tibble(a = 1, b = NULL)
#> All columns in a tibble must be 1d or 2d objects:
#> * Column `b` is NULL

You can work this by using list column if you really need to have NULL value in data.frame.

library(magrittr)
list('col1' = 2, 'col2' = NULL, col3 = 'wow') %>% 
  tibble::enframe() %>%
  tidyr::spread(name, value)
#> # A tibble: 1 x 3
#>   col1      col2   col3     
#>   <list>    <list> <list>   
#> 1 <dbl [1]> <NULL> <chr [1]>

You'll have to deal with list column after.

6 Likes

Very similar to cderv's answer, you could do:

library(magrittr)

list('col1' = 2, 'col2' = NULL, col3 = 'wow') %>% 
  purrr::modify_if(is.null, list) %>% 
  tibble::as_tibble()
#> # A tibble: 1 x 3
#>    col1 col2   col3 
#>   <dbl> <list> <chr>
#> 1     2 <NULL> wow

Created on 2019-06-07 by the reprex package (v0.3.0)

4 Likes

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