在学习R的过程中遇到了几个有意思“非空”对象,现将其呈现出来,希望大家一起讨论并批评指正:
<br />
# 创建第一个“非空”对象<br />
test1 <- numeric(0)<br />
test1 ## numeric(0)<br />
# 创建第二个<br />
## rep()函数作用于test1,没有出现想象中的“test1”重复两次<br />
rep(test1, 2) # numeric(0)<br />
test2 <- matrix(test1, nrow = 2)<br />
test2<br />
## [,1]<br />
## [,2]<br />
test2_2 <- matrix(test1, ncol = 2)<br />
test2_2 ## [,1] [,2]<br />
# 创建第三个,将以上三个对象组成一个列表<br />
t3 <- list(t1 = test1, t2 = test2, t2 = test2_2)<br />
t3<br />
# 检验以上对象是否为空<br />
is.null(test1); is.null(test2); is.null(test2_2); is.null(test3)<br />
## [1] FALSE<br />
## [1] FALSE<br />
## [1] FALSE<br />
## [1] FALSE<br />
# 检验它们是否为NA;<br />
is.na(test1); is.na(test2); is.na(test2_2); is.na(test3)<br />
## logical(0)<br />
## [1,]<br />
## [2,]<br />
## [,1] [,2]<br />
## t1 t2 t2<br />
## FALSE FALSE FALSE<br />
# 查看对象的长度<br />
length(test1); length(test2); length(test2_2); length(test3)<br />
## [1] 0<br />
## [1] 0<br />
## [1] 0<br />
## [1] 3<br />
</p>
小小的补充说明:
1 实质上,以上所谓的“非空”对象不过是创建了长度为0的对象(除了test3);对于列表也可以创建长度为0的对象,比如list(),区别于查看list函数的代码;并且,可以创建长度为1的matrix,比如matrix(),但这个创建的对象用is.na()检验为TRUE;
2 is.na(test3[[1]])出现情理之中的logical(0); 同时,可以用logical(0)创建长度为0的逻辑对象;所以,可以创建长度为0的向量,比如vector(0);
3 至于data.frame,可以用as.data.frame(test2), as.data.frame(test2_2),创建的对象也很好玩;
4 为什么要啰啰嗦嗦说这么多,在编程中时常会遇到这些问题,比如:在保存循环结果时候,时常会现创建一个类似test1(或者list())的对象,然后每次循环的结果依次存入。再比如,在筛选某种符合限定条件的对象时,可能出现类似于test2或者test2_2
<br />
testa <- list()<br />
for(i in 1:10) testa[[i]] <- seq(i)<br />
testa<br />
# 以上也可以用lapply(1:10, seq)实现<br />
testb <- matrix(c(1, NA, 3, NA), 2)<br />
# 以下结果类似test2_2<br />
testb[testb[, 1] > 2 && !is.na(testb[, 1]), ]<br />
</p>