从R

时间:2019-08-29 19:49:40

标签: r list

这似乎与SE的许多主题有所不同,但是我还没有看到专门解决我所遇到的问题的一个。我有一个列表列表:

mylist <- list(list(`1` = 2:3, `2` = 4:5, `3` = 6:7, `4` = 8:10), list(
    `1` = 11:12, `2` = 13:14, `3` = 15:16, `4` = 17:18, `5` = 19:20, 
    `6` = 21:22), list(`1` = 23:24))

我想删除内部某些包含在其他向量中的所有子元素。例如,如果要删除的元素是c(4,5,19,20,23,24),那么我期望输出:

list(list(`1` = 2:3, `3` = 6:7, `4` = 8:10), list(
    `1` = 11:12, `2` = 13:14, `3` = 15:16, `4` = 17:18, 
    `6` = 21:22))

删除名称也可以。我尝试了很多事情,包括:

removeListElem <- function(inlist,elem_remove){
  lapply(inlist,setdiff,elem_remove)
}

lapply(mylist,function(x) removeListElem(x,c(4,5,19,20,23,24)))

但是它会产生输出

list(list(`1` = 2:3, `2` = integer(0), `3` = 6:7, `4` = 8:10), 
    list(`1` = 11:12, `2` = 13:14, `3` = 15:16, `4` = 17:18, 
        `5` = integer(0), `6` = 21:22), list(`1` = integer(0)))

然后我可以过滤掉{p {1}}。

是否有 clean efficiency (不执行嵌套lapply的)解决方案来删除列表列表中的给定元素集?

1 个答案:

答案 0 :(得分:3)

我们可以将内部列表的清理功能整合到您的函数中:

removeListElem <- function(inlist,elem_remove){
  outlist = lapply(inlist,setdiff,elem_remove)
  outlist[lengths(outlist) > 0]
}

这可以照顾integer(0),但是在结果中仍然会提供一个空列表:

result = lapply(mylist,function(x) removeListElem(x,c(4,5,19,20,23,24)))
result
# [[1]]
# [[1]]$`1`
# [1] 2 3
# 
# [[1]]$`3`
# [1] 6 7
# 
# [[1]]$`4`
# [1]  8  9 10
# 
# 
# [[2]]
# [[2]]$`1`
# [1] 11 12
# 
# [[2]]$`2`
# [1] 13 14
# 
# [[2]]$`3`
# [1] 15 16
# 
# [[2]]$`4`
# [1] 17 18
# 
# [[2]]$`6`
# [1] 21 22
# 
# 
# [[3]]
# named list()

所以我们可以用类似的方式清理结果:

result[lengths(result) > 0]
# [[1]]
# [[1]]$`1`
# [1] 2 3
# 
# [[1]]$`3`
# [1] 6 7
# 
# [[1]]$`4`
# [1]  8  9 10
# 
# 
# [[2]]
# [[2]]$`1`
# [1] 11 12
# 
# [[2]]$`2`
# [1] 13 14
# 
# [[2]]$`3`
# [1] 15 16
# 
# [[2]]$`4`
# [1] 17 18
# 
# [[2]]$`6`
# [1] 21 22

这就像您的尝试一样,使用嵌套的lapply。我们当然可以将它们打包成一个函数:

removeListElemComplete = function(inlist, elem_remove) {
  outlist = lapply(inlist, removeListElem, elem_remove = elem_remove)
  outlist[lengths(outlist) > 0]
}

removeListElemComplete(mylist, c(4,5,19,20,23,24))
# [[1]]
# [[1]]$`1`
# [1] 2 3
# 
# [[1]]$`3`
# [1] 6 7
# 
# [[1]]$`4`
# [1]  8  9 10
# 
# 
# [[2]]
# [[2]]$`1`
# [1] 11 12
# 
# [[2]]$`2`
# [1] 13 14
# 
# [[2]]$`3`
# [1] 15 16
# 
# [[2]]$`4`
# [1] 17 18
# 
# [[2]]$`6`
# [1] 21 22