Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove empty lists from a tibble in R

I am trying to remove any list from my tibble that has "<chr [0]>"

library(tidyverse)

df <- tibble(x = 1:3, y = list(as.character()), 
             z=list(as.character("ATC"),as.character("TAC"), as.character()))
df
#> # A tibble: 3 × 3
#>       x y         z        
#>   <int> <list>    <list>   
#> 1     1 <chr [0]> <chr [1]>
#> 2     2 <chr [0]> <chr [1]>
#> 3     3 <chr [0]> <chr [0]>

Created on 2022-02-15 by the reprex package (v2.0.1)

I want my tibble to look like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#> # A tibble: 3 × 3
#>       x  z        
#>    <int> <list>   
#> 1     1 <chr [1]>
#> 2     2 <chr [1]>
#> 3     3    NA

any help is appreciated

>Solution :

You can do:

df %>%
  select(where(~!all(lengths(.) == 0))) %>%
  mutate(z = lapply(z, function(x) ifelse(length(x) == 0, NA, x)))

# A tibble: 3 x 2
      x z        
  <int> <list>   
1     1 <chr [1]>
2     2 <chr [1]>
3     3 <lgl [1]>

Note, in your z column you can‘t have list elemtents for row 1 and 2 and a direct logical value NA. The whole column needs to be a list.

If all elements of z have only one element, you can add another line of code with mutate(z = unlist(z)).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading