'&' and '&&' indicate logical AND and '|' and '||' indicate logical OR. The shorter form performs elementwise comparisons in much the same way as arithmetic operators. The longer form evaluates left to right examining only the first element of each vector. Evaluation proceeds only until the result is determined. The longer form is appropriate for programming control-flow and typically preferred in 'if' clauses.
有一点要注意的是, if(cond) expr 在这个语句中,cond是 “A length-one logical vector that is not 'NA'. Conditions of length greater than one are accepted with a warning, but only the first element is used. Other types are coerced to logical if possible, ignoring any class” if(sh2$PROVINCE==21 & sh2$HUKOU==1) sh2$PROVINCE和sh2$HUKOU恐怕都应该是向量,在使用if的时候可能会出现这样的警告: ”Warning message: In if (x == 1) x <- x * 10 : 条件的长度大于一,因此只能用其第一元素“ 如果用循环的话,不妨这样 for(i in 1:N) { if(sh2$PROVINCE==21 & sh2$HUKOU==1) .... } 这样做效率差一些,呵呵