Home > Enterprise >  R: How to remove nested lists from columns?
R: How to remove nested lists from columns?

Time:03-11

I am looking to remove nested list columns from a tibble with lists. For example in the list below I want to remove "affected_rows" without specifically referencing the column name. How would i best approach this?

my_list <- list(
  a =
    tibble(
      code = c("ax","yz"),
      affected_rows =
        c(list(1:10),list(200))
    ),
  b = 
    tibble(
      workid = c("123","456"),
      sheet = c("sheet1", "sheet2")
    )
)

CodePudding user response:

Another possible solution:

library(tidyverse)
  
map(my_list, ~ .x %>% mutate(across(where(is.list), as.null))) 

#> $a
#> # A tibble: 2 × 1
#>   code 
#>   <chr>
#> 1 ax   
#> 2 yz   
#> 
#> $b
#> # A tibble: 2 × 2
#>   workid sheet 
#>   <chr>  <chr> 
#> 1 123    sheet1
#> 2 456    sheet2

CodePudding user response:

in base R:

lapply(my_list, Filter, f = Negate(is.list))

$a
# A tibble: 2 x 1
  code 
  <chr>
1 ax   
2 yz   

$b
# A tibble: 2 x 2
  workid sheet 
  <chr>  <chr> 
1 123    sheet1
2 456    sheet2

CodePudding user response:

We can use select after looping over the list

library(dplyr)
library(purrr)
my_list <- map(my_list, ~ .x %>%
     select(-where(is.list)))

-output

my_list
$a
# A tibble: 2 × 1
  code 
  <chr>
1 ax   
2 yz   

$b
# A tibble: 2 × 2
  workid sheet 
  <chr>  <chr> 
1 123    sheet1
2 456    sheet2

Or negate the output of where

my_list <- map(my_list,  ~.x %>% 
      select(negate(where(is.list))))
my_list
$a
# A tibble: 2 × 1
  code 
  <chr>
1 ax   
2 yz   

$b
# A tibble: 2 × 2
  workid sheet 
  <chr>  <chr> 
1 123    sheet1
2 456    sheet2

Or a more compact option with discard

map(my_list, discard, is.list)
$a
# A tibble: 2 × 1
  code 
  <chr>
1 ax   
2 yz   

$b
# A tibble: 2 × 2
  workid sheet 
  <chr>  <chr> 
1 123    sheet1
2 456    sheet2

Or may use atomic_elem from collapse

library(collapse)
map(my_list, atomic_elem, keep.class = TRUE)
$a
# A tibble: 2 × 1
  code 
  <chr>
1 ax   
2 yz   

$b
# A tibble: 2 × 2
  workid sheet 
  <chr>  <chr> 
1 123    sheet1
2 456    sheet2
  • Related