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

时间:2019-10-28 14:07:29

标签: 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"))
  )

我正在遍历l_of_lists的{​​{1}},以确定每个数据帧的列数,并且我要删除每个不满足条件的sublists < / em>(在此示例中,它具有三列)。

具有以下代码:

sublist

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

2 个答案:

答案 0 :(得分:6)

更容易调用没有3列的元素:

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

使用sapply,您遍历l_of_list的每个元素以获取具有列数的向量。您可以使用它来对具有3列的内容进行子集化。

如果要删除,请尝试此

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

答案 1 :(得分: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
    }
  }
}