2015-04-06 221 views
2

我想我必须使用少量语法糖的问题[R]:X ||Ÿ与mapply(函数(X,Y)X || Y,X,Y)在[R]

x=rnorm(1000,mean = 1,sd = 1) 
y=rnorm(1000,mean = 1,sd = 1) 
x=x>1 
y=y>1 
x||y 
mapply(function(x,y) x||y,x,y) 

基本上我想获得布尔类型的列表,其中的元素是TRUE时无论是在x和y的相应元素是TRUE

x||y 

返回TRUE而

标量值
mapply(function(x,y) x||y,x,y) 

完成这项工作。

所以我怎么弄错的

x||y 

语法?

非常感谢......

回答

2

你可以做x | y获得量化的结果。 x || y仅将x的第一个元素与y的第一个元素进行比较。

要理解这一点,考虑以下因素:

TRUE | FALSE 
# [1] TRUE 
TRUE || FALSE 
# [1] TRUE 

c(TRUE, FALSE) | c(TRUE, FALSE) 
# [1] TRUE FALSE 
c(TRUE, FALSE) || c(TRUE, FALSE) # only first element is compared 
# [1] TRUE 

c(FALSE, TRUE) | c(FALSE, TRUE) 
# [1] FALSE TRUE 
c(FALSE, TRUE) || c(FALSE, TRUE) # only first element is compared 
# [1] FALSE 

mapply在这里不需要,因为这只是重建的|行为:

identical(c(FALSE, TRUE) | c(FALSE, TRUE), mapply(function(x,y) x || y, c(FALSE, TRUE),c(FALSE, TRUE))) 
# [1] TRUE 
identical(c(TRUE, FALSE) | c(FALSE, TRUE), mapply(function(x,y) x || y, c(TRUE, FALSE),c(FALSE, TRUE))) 
# [1] TRUE 

mapply也更耗费计算:

microbenchmark::microbenchmark(mapply(function(x,y) x||y, x, y), x | y) 
Unit: microseconds 
           expr  min  lq  mean median  uq  max neval cld 
mapply(function(x, y) x || y, x, y) 1495.294 1849.006 2186.77275 2012.776 2237.936 5320.702 100 b 
           x | y 27.713 28.868 39.97163 33.871 38.297 166.657 100 a 
+0

Hi Thomas,tha很多 - 虽然我认为帕斯卡的解释是正确的。 – 2015-04-06 08:43:11

+0

@RomeoKienzler不,这不是严格正确的。 – Thomas 2015-04-06 08:48:42

+0

@Thomas是对的。 – 2015-04-06 09:09:41

相关问题