删除包含矩阵的某些元素的子列表

时间:2017-03-21 22:22:14

标签: r list matrix

考虑矩阵:

badcombos
      [,1]      [,2] 
[1,] "Red"    "Yellow"
[2,] "Green"  "Yellow"
[3,] "Orange" "Yellow"
[4,] "Blue"   "Green"
[5,] "Blue"   "Purple"

然后,列表:

allcombos
[[1]]
[1] "Red" "Green" "Orange" "Pink" "Purple"
[[2]]
[1] "Red" "Red" "Brown" "Purple" "Pink"
[[3]]
[1] "Yellow" "Red" "Brown" "Blue" "Purple"
[[4]]
[1] "Yellow" "Green" "Blue" "Purple" "Gold"
....
[[k]] "Red" "Blue" "Orange" "Brown" "Pink

我将如何减少"基于条件的列表,如果badcombos矩阵中的任何颜色组合出现在列表中(即上例中的子列表[[3]]和[[4]]),则它们将从列表中删除。

编辑 - 完整代码:

my_list = list()
my_list[[1]] = c("Red","Green","Orange","Pink","Purple")
my_list[[2]] = c("Red","Red","Brown","Purple","Pink")
my_list[[3]] = c("Yellow","Red","Brown","Blue","Purple")
my_list[[4]] = c("Yellow","Green","Blue","Purple","Gold")
my_list[[5]] = c("Red","Blue","Orange","Brown","Pink")

my_matrix = t(matrix(c("Red","Yellow","Green","Yellow","Orange","Yellow","Blue","Green","Blue","Purple"),2,5))

2 个答案:

答案 0 :(得分:2)

另一种方法:

match_first_col  <- lapply(my_list,match,my_matrix[,1])
match_second_col <- lapply(my_list,match,my_matrix[,2])

#Elements of the list that match both columns:
is.na(mapply(intersect, match_first_col,match_second_col))
[1]  TRUE  TRUE FALSE FALSE  TRUE

#Keep only allcombos with no match in first and second column
my_list[is.na(mapply(intersect, match_first_col,match_second_col))]

[[1]]
[1] "Red"    "Green"  "Orange" "Pink"   "Purple"

[[2]]
[1] "Red"    "Red"    "Brown"  "Purple" "Pink"  

[[3]]
[1] "Red"    "Blue"   "Orange" "Brown"  "Pink" 

答案 1 :(得分:1)

以下是使用%in%检查“错误”列表中哪些值存在的尝试:

sel <- mapply(
  function(a,b) all(rowSums(matrix(b %in% a,ncol=2))<2),
  my_list, list(my_matrix)
)
#[1]  TRUE  TRUE FALSE FALSE  TRUE

然后选择你想要的那些:

my_list[sel]