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

将R`outer`与“%in%”运算符一起使用

r
  •  0
  • asachet  · 技术社区  · 7 年前

    我正在尝试执行以下外部操作:

    x <- c(1, 11)
    choices <- list(1:10, 10:20)
    
    outer(x, choices, FUN=`%in%`)
    

    我期望以下矩阵:

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

    outer(x, choices, FUN=paste, sep=" %in% ")
         [,1]           [,2]           
    [1,] "1 %in% 1:10"  "1 %in% 10:20" 
    [2,] "11 %in% 1:10" "11 %in% 10:20"
    

          [,1]  [,2]
    [1,] FALSE FALSE
    [2,] FALSE FALSE
    

    发生了什么事?

    2 回复  |  直到 7 年前
        1
  •  3
  •   nicola    7 年前

    如评论中所述 table match (由调用的函数 %in% )不打算成为列表(如果是,则强制为字符)。你应该使用 vapply

    vapply(choices,function(y) x %in% y,logical(length(x)))
    #      [,1]  [,2]
    #[1,]  TRUE FALSE
    #[2,] FALSE  TRUE
    
        2
  •  2
  •   Sotos    7 年前

    另一种接近你思路的方法是 expand.grid() 创建组合,然后 Map %in% 功能,即。

    d1 <- expand.grid(x, choices)
    matrix(mapply(`%in%`, d1$Var1, d1$Var2), nrow = length(x))
    #or you can use Map(`%in%`, ...) in order to keep results in a list
    

    d1 <- expand.grid(list(x), choices) 
    mapply(%in%, d1$Var1, d1$Var2)
    

    都是给予,,

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