r4ds / mentordash

Other
9 stars 4 forks source link

Question from Cory Pilat (UT1RDKRGS) #87

Open jonthegeek opened 8 months ago

jonthegeek commented 8 months ago

Hey there, i'm having some list struggles at the moment and curious everyones thoughts. I have a list of lists, and the sublists all follow the same structure:

dat <- list(list(a = NULL, 
                 b = data.frame(x = c(1:10), 
                                y = c(1:10)), 
                 c = NULL), 
            list(a = data.frame(x = c(1:10), 
                                y = c(1:10)), 
                 b = NULL, 
                 c = data.frame(x = c(1:10), 
                                y = c(1:10))), 
            list(a = NULL, 
                 b = NULL, 
                 c = data.frame(x = c(1:10), 
                                y = c(1:10))), 
            list(a = data.frame(x = c(1:10), 
                                y = c(1:10)), 
                 b = data.frame(x = c(1:10), 
                                y = c(1:10)), 
                 data.frame(x = c(1:10), 
                            y = c(1:10))))

So each sublist has a, b, c. Sometimes they can be null other times they'll have a dataframe (well tibble in my actual case). What I want to do is create 3 new objects that extract the "a", "b", "c" respectively. I'm expecting it to be a list type but I can't quite seem to puzzle out how to extract the sublist based on the name of the list. I'm trying to do something like the following:

a <- dat |> 
  purrr::keep(\(x) names(x) == "a")

but this won't work because the names(x) returns a vector of length three and isn't necessarily a predicate function. I almost need just a singular "name" rather than "names" here. Any thoughts? Ultimately, i'm hoping to have an output like:

a <- list(a = NULL, 
          a = data.frame(x = c(1:10), 
                         y = c(1:10)), 
          a = NULL, 
          a = data.frame(x = c(1:10), 
                         y = c(1:10)))

b <- list(b = data.frame(x = c(1:10), 
                         y = c(1:10)), 
          b = NULL,
          b = NULL,
          b = data.frame(x = c(1:10), 
                         y = c(1:10)))

d <- list(d = NULL, 
          d = data.frame(x = c(1:10), 
                         y = c(1:10)), 
          d = data.frame(x = c(1:10), 
                         y = c(1:10)), 
          d = data.frame(x = c(1:10), 
                         y = c(1:10)))