从for循环中的列表列表中删除元素

Ivo*_*Ivo 4 r list

我有一个(数据帧)列表的命名列表。

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"))
  )
Run Code Online (Sandbox Code Playgroud)

我遍历l_of_listssublists确定每个数据帧的列数,我想删除每一个sublist不符合条件(在这个例子是,它有三列)。

使用以下代码:

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
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

如何删除根据条件确定的子列表?(我敢肯定有一种更有效的方法可以完成此操作,我很高兴收到有关此操作的提示。)

Stu*_*olf 6

调用没有3列的元素会容易得多:

lapply(l_of_lists,function(i)i[sapply(i,length)==3])
Run Code Online (Sandbox Code Playgroud)

有了sapply,您就可以遍历l_of_list的每个元素以获得列数的向量。您可以使用此子集来划分具有3列的那些子集。

如果要删除,请尝试此操作

l_of_lists = lapply(l_of_lists,function(i)i[sapply(i,length)==3])
Run Code Online (Sandbox Code Playgroud)

  • 虽然我认为这是最好的解决方案,但它并没有回答专门询问如何删除 for 循环中的项目的问题。 (2认同)
  • @camille我从来没有说过它们是......我只是指出这个答案并没有回答想要了解for循环的问题。我还说过,这是比使用 for 循环更好的解决方案。是什么让你感到困惑? (2认同)

roo*_*kie 5

如果要使用循环,那么最好使用索引而不是对象:

for (i in 1:length(l_of_lists)){
  sublist = l_of_lists[[i]]
  for (j in 1:length(sublist)){
    obj = sublist[[j]]
    if (!ncol(obj) == 3)
    {
      print(ncol(obj))
      l_of_lists[[i]][[j]] <- NULL # this does achieve the desired result
    }
  }
}
Run Code Online (Sandbox Code Playgroud)