How to remove a level of lists from a list of lists
I think this does the trick
new.pp <- unlist(pp,recursive=FALSE)
how to remove elements in list of lists of nested lists?
This is the right scenario to use modify_depth
, which functions as a shortcut for chains of modify
to access deep nested lists. modify
has an advantage over map
in this problem because it will preserve the type of the input instead of coercing everything to lists, which may be relevant if you have vector elements of your list structure.
Using your given input (with a p3
element inside rather than on the same level as p2
), the dataframe elements at the second and third levels are discard
ed as below. In order to search all levels of the nested list, we can set up a while
loop to iterate through the levels, discarding dataframes as we go. We need .ragged = TRUE
to deal with errors with list depth. This version searches bottom up but you could change it to search top down as well.
library(tidyverse)
x <- list(
p1 = list(type = "A", score = list(c1 = 10, c2 = 8, c3 = data.frame(a = 1, b = 3, c = 5))),
p2 = list(
type = "B", score = list(c1 = 9, c2 = 9, c3 = data.frame(a = 2, b = 2)),
p3 = list(type = "B", score = list(c1 = 9, c2 = 7, c3 = data.frame(a = 2, b = 2)))
)
)
remove_dataframes <- function(input_list) {
current_list <- input_list
current_depth <- vec_depth(current_list)
# current_depth <- max_depth
while (current_depth > 1) {
current_list <- modify_depth(
.x = current_list,
.depth = current_depth,
.f = ~ discard(., is.data.frame),
.ragged = TRUE
)
current_depth <- current_depth - 1
}
return(current_list)
}
x %>%
remove_dataframes %>%
glimpse
#> List of 2
#> $ p1:List of 2
#> ..$ type : chr "A"
#> ..$ score:List of 2
#> .. ..$ c1: num 10
#> .. ..$ c2: num 8
#> $ p2:List of 3
#> ..$ type : chr "B"
#> ..$ score:List of 2
#> .. ..$ c1: num 9
#> .. ..$ c2: num 9
#> ..$ p3 :List of 2
#> .. ..$ type : chr "B"
#> .. ..$ score:List of 2
Created on 2019-02-20 by the reprex package (v0.2.1)
Removing NA from list of lists in R in function
Use rapply
:
rapply(L.miss, na.omit, how = "replace")
Related Topics
How Make 2 Column Layout in R Markdown When Rendering PDF
Include Data Examples in Developing R Packages
How to Run an 'R' Script Without Suppressing Output
How to Automate Multiple Requests to a Web Search Form Using R
How to Create a Pivot Table in R with Multiple (3+) Variables
Ggplot: Multiple Years on Same Plot by Month
Check If Each Row of a Data Frame Is Contained in Another Data Frame
Highlight (Shade) Plot Background in Specific Time Range
How to Make a Dummy Variable in R
Cannot Install R Packages in Jupyter Notebook
In R, How to Subset a Data.Frame by Values from Another Data.Frame
Unnest a List Column Directly into Several Columns
Read CSV with Dates and Numbers
Create an Expression from a Function for Data.Table to Eval
Importing Only Every Nth Row from a .CSV File in R
Adjusting Width of Tables Made with Kable() in Rmarkdown Documents