R中的NA值表示“不可用”,表示缺少值。如果一个向量甚至只有一个NA值,那么对该向量的计算就会有些困难,因为在计算过程中我们要么必须删除该NA,要么替换它,或者忽略它。要执行任何这些操作,我们将必须对代码进行一些更改,因此,最好在执行任何操作之前检查向量是否包含NA。这可以通过any函数与is.na结合使用来完成。
> x1<-c(1,2,3,2) > x1 [1] 1 2 3 2 > any(is.na(x1)) [1] FALSE > x2<-c(1,2,3,2,NA) > x2 [1] 1 2 3 2 NA > any(is.na(x2)) [1] TRUE > x3<-c(4,5,6,"",2,8,7) > x3 [1] "4" "5" "6" "" "2" "8" "7" > any(is.na(x3)) [1] FALSE > x4<-c(4,5,6,"NA",2,8,7) > x4 [1] "4" "5" "6" "NA" "2" "8" "7" > any(is.na(x4)) [1] FALSE > x5<-c(4,5,6,4,2,8,7,NA,4,5,NA,NA) > x5 [1] 4 5 6 4 2 8 7 NA 4 5 NA NA > any(is.na(x5)) [1] TRUE > x6<-rep(c(15,NA,10),times=10) > x6 [1] 15 NA 10 15 NA 10 15 NA 10 15 NA 10 15 NA 10 15 NA 10 15 NA 10 15 NA 10 15 [26] NA 10 15 NA 10 > any(is.na(x6)) [1] TRUE > x7<-rep(c(15,"NA",10),times=10) > x7 [1] "15" "NA" "10" "15" "NA" "10" "15" "NA" "10" "15" "NA" "10" "15" "NA" "10" [16] "15" "NA" "10" "15" "NA" "10" "15" "NA" "10" "15" "NA" "10" "15" "NA" "10" > any(is.na(x7)) [1] FALSE > x8<-1:1000000 > any(is.na(x8)) [1] FALSE > x9<-rep(c(1,2,3,4,5,6,7,8,9,10),times=500000) > any(is.na(x9)) [1] FALSE > x10<-rep(c(1,2,3,4,5,6,7,8,9,10),times=5000000) > any(is.na(x10)) [1] FALSE
另一方面,具有小尺寸的向量将花费较少的时间来获得答案,而具有大尺寸的向量将花费更多的时间以使我们知道我们的向量中是否具有NA。