例如,如果我有
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 元素为length
1(即它将元素回收为 lhs 元素的长度)时,它就会起作用。 对象 'com' 和 'ovals' 在length
上是不同的,而 'ovals' 不是length
1。 因此,我们可以循环"椭圆形"的元素,进行==
并获得mean
mean(sapply(ovals, function(x) com == x))
或者没有 lambda 函数
mean(sapply(ovals, `==`, com))
我们还可以将逻辑list
元素Reduce
到单个向量中
mean(Reduce(`|`, lapply(ovals, `==`, com)))