【问题标题】:Removing sublists that contain certain elements of a matrix删除包含矩阵某些元素的子列表
【发布时间】:2017-03-21 22:22:13
【问题描述】:

考虑矩阵:

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))

【问题讨论】:

  • 请使用dput 提供badcombosallcombos。 (即编辑您的帖子并添加dput(badcombos)dput(allcombos) 的结果。
  • 我只把它们作为理论向量和矩阵,因为我使用的要复杂得多。
  • @Aesler ,Luke 打算将 dput 作为示例发布,以便我们更轻松地解决问题。否则,我们必须创建对象。
  • 好的,我只是用完整的代码快速编辑了它:)

标签: r list matrix


【解决方案1】:

另一种方法:

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" 

【讨论】:

    【解决方案2】:

    这是使用%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]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-09
      • 1970-01-01
      • 2018-09-04
      • 1970-01-01
      • 2014-04-12
      • 2013-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多