代码之家  ›  专栏  ›  技术社区  ›  Serhii

将列表中每个成员的每个元素与另一个列表中每个成员的每个元素进行比较[重复]

  •  1
  • Serhii  · 技术社区  · 7 年前

    我想将列表中每个成员的每个元素与另一个列表中每个成员的每个元素进行比较。

    A = B = list(1, 2, c(1,2))
    

    预期结果如下:

          [,1]  [,2]  [,3]
    [1,]  TRUE FALSE  TRUE
    [2,] FALSE  TRUE  TRUE
    [3,]  TRUE  TRUE  TRUE
    

    我可以为data.frame解决类似的任务:

    df = data.frame(A = c(1, 2, "1,2"), B = c(1, 2, "1,2"))
    sapply(df$A, grepl, df$B)
    

    它给出:

          [,1]  [,2]  [,3]
    [1,]  TRUE FALSE FALSE
    [2,] FALSE  TRUE FALSE
    [3,]  TRUE  TRUE  TRUE
    

    但这并不是我想要的解决方案。

    非常感谢您的帮助!

    1 回复  |  直到 7 年前
        1
  •  2
  •   Andre Elrico    7 年前

    这里有一个复杂的方法:

    A = B = list(1, 2, c(1,2))
    
    outer(A, B, function(a,b) sapply((Vectorize(`%in%`))(a,b),any) )
    
    #      [,1]  [,2] [,3]
    #[1,]  TRUE FALSE TRUE
    #[2,] FALSE  TRUE TRUE
    #[3,]  TRUE  TRUE TRUE
    

    这里有一个简单的方法:

    eg <- expand.grid(A,B)
    matrix(
        mapply(function(x,y) {any(x %in% y)}, x = eg$Var1, y = eg$Var2 ), nrow = length(A), ncol = length(B)
    )
    

    (只是为了好玩:)

    matrix(
        mapply(function(x,y) {length(intersect(x, y)) != 0}, x = eg$Var1, y = eg$Var2 ), nrow = length(A), ncol = length(B)
    )