The difference between & and && in R

后端 未结 3 1932
鱼传尺愫
鱼传尺愫 2020-12-11 19:56

I have read

http://stat.ethz.ch/R-manual/R-devel/library/base/html/Logic.html

and the difference between & and && doesn\'t make sense. For examp

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-11 20:13

    The "&" operator is only an element -by-element logical AND when the vectors are of equal length. That why you should also expect this result:

     c(0,1,2,3,4) & 1
    [1] FALSE  TRUE  TRUE  TRUE  TRUE  # due to argument recycling
    

    Notice that it is not comparing numerical values but only after coercion to type "logical", and any non-zero value will be TRUE:

    seq(0,1,by=.2) & -1
    [1] FALSE  TRUE  TRUE  TRUE  TRUE  TRUE
    

    "&&" only compares the first element of its first argument to the first argument of the second and issues a warning (but not an error) if either are longer than a single element.

    If you want to test for equality then use "==".

提交回复
热议问题