Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete elements from list of lists from within for-loop

Tags:

list

r

I have a named list of lists (of data frames).

l_of_lists <- list(
  fruits = list(
      red = data.frame("apple", "cherry", "strawberry"),
      yellow = data.frame("banana", "lemon"),
      orange = data.frame("orange", "grapefruit", "blood orange")),
  colors = list(
      green = data.frame("light green", "green", "dark green"),
      red = data.frame("red", "dark red"),
      blue = data.frame("light blue", "blue", "dark blue")),
  places = list(
    inside = data.frame("living room", "bathrooom", "kitchen"),
    outside = data.frame("garden", "yard"),
    neighborhood = data.frame("playground", "shop", "school"))
  )

I am looping over l_of_lists's sublists to determine the number of columns of each data frame and I want to delete each sublist which does not fulfill the condition (which in this example is that it has three columns).

with the following code:

for (ls in l_of_lists){
  for (sublist in ls){
    if (!ncol(sublist) == 3)
    {
      print(ncol(sublist))
      #sublist <- NULL # this does achieve the desired result
    }
  }
}

How can I delete the sublist I identified with the condition? (I'm sure there is a more efficient way to accomplish this and I'm happy for hints regarding this.)

like image 540
Ivo Avatar asked Dec 18 '22 15:12

Ivo


1 Answers

Much easier to call you the elements which does not have 3 columns:

lapply(l_of_lists,function(i)i[sapply(i,length)==3])

With the sapply, you loop through each element of l_of_list to get a vector of number of columns. You use this to subset on those that have 3 columns.

And if you want to delete, try this

l_of_lists = lapply(l_of_lists,function(i)i[sapply(i,length)==3])
like image 143
StupidWolf Avatar answered Feb 05 '23 00:02

StupidWolf