r语言 - 应用于类型为"NULL"的非(列表或向量)的 is.na()是什么意思?



我想从没有NA的data.frame中选择具有前向过程的Cox模型。以下是一些示例数据:

test <- data.frame(
  x_1   = runif(100,0,1),
  x_2   = runif(100,0,5),
  x_3   = runif(100,10,20),
  time  = runif(100,50,200),
  event = c(rep(0,70),rep(1,30))
)

这个表没有任何意义,但是如果我们试图建立一个模型:

modeltest <- coxph(Surv(time, event) ~1, test)
modeltest.forward <- step(
  modeltest, 
  data      = test, 
  direction = "forward", 
  scope     = list(lower = ~ 1, upper = ~ x_1 + x_2 + x_3)
)

在第一步结束,并说:

在is.na(fit$coefficients)中:is.na()适用于类型为'NULL'的非(列表或向量)

(三次)

我试着改变上层模型,我甚至试过upper = ~ 1,但警告仍然存在。我不明白:我没有NAs,我的向量都是数字(我检查过了)。我搜索了人们是否有同样的问题,但我所能找到的都是由于向量的名称或类而导致的问题。

我的代码有什么问题?

这种情况下的问题

公式的右侧是1,这使它成为null模型coxph调用coxph.fit,这(也许懒惰)不麻烦返回null模型的系数。

之后coxph调用extractAIC,后者错误地假定模型对象包含一个名为coefficients的元素。

一般情况

is.na假定它的输入参数是原子向量、矩阵、列表或data.frame。其他数据类型会导致警告。它发生在NULL上,如您所见:

is.na(NULL)
## logical(0)
## Warning message:
## In is.na(NULL) : is.na() applied to non-(list or vector) of type 'NULL'

这个问题的一个常见原因是试图访问列表中的元素,或者数据框架中不存在的列。

d <- data.frame(x = c(1, NA, 3))
d$y # "y" doesn't exist is the data frame, but NULL is returned
## NULL
is.na(d$y)
## logical(0)
## Warning message:
## In is.na(d$y) : is.na() applied to non-(list or vector) of type 'NULL'

您可以通过在操作该列之前检查该列是否存在来防止这种情况。

if("y" in colnames(d))
{
  d2 <- d[is.na(d$y), ]
}

带有其他数据类型的警告

对于公式、函数、表达式等,会得到类似的警告:

is.na(~ NA)
## [1] FALSE FALSE
## Warning message:
## In is.na(~NA) : is.na() applied to non-(list or vector) of type 'language'
is.na(mean)
## [1] FALSE
## Warning message:
## In is.na(mean) : is.na() applied to non-(list or vector) of type 'closure'
is.na(is.na)
## [1] FALSE
## Warning message:
## In is.na(is.na) : is.na() applied to non-(list or vector) of type 'builtin'
is.na(expression(NA))
## [1] FALSE
## Warning message:
## In is.na(expression(NA)) :
##   is.na() applied to non-(list or vector) of type 'expression'

最新更新