如何使 == 和 %in% 执行相同的操作

  • 本文关键字:操作 %in% 何使 执行 r
  • 更新时间 :
  • 英文 :


例如,如果我有

colors <- c("Blue", "Red", "Yellow", "Green")
shapes <- c("Square", "Circle", "Triangle", "Diamond", "Star", "Pentagon", "Oval")
(com <- expand.grid(color=colors, shape=shapes)) #data frame from all combinations
(com <- paste(com$color, com$shape))
(ovals <- paste("Oval", shapes))

我将如何使用==返回与mean(com %in% ovals)相同的内容?

==是元素运算符。 当我们对 lhs 和 rhs 上的参数具有相同的长度时,或者如果 rhs 元素为length1(即它将元素回收为 lhs 元素的长度)时,它就会起作用。 对象 'com' 和 'ovals' 在length上是不同的,而 'ovals' 不是length1。 因此,我们可以循环"椭圆形"的元素,进行==并获得mean

mean(sapply(ovals, function(x) com == x))

或者没有 lambda 函数

mean(sapply(ovals, `==`, com))

我们还可以将逻辑list元素Reduce到单个向量中

mean(Reduce(`|`, lapply(ovals, `==`, com)))

最新更新