2

如何检查 R 数据框是否为空?查看此代码。我想对其进行修改,使其永远不会产生错误或警告。

x = sample(1:2,1)
d = NA
if(x == 1) {
    d = data.frame("h"=c(1,2),"q"=c(2,3))
}

#check if data frame is NA
if(is.na(d)) {
    print("d is NA")
}

如果x == 1,那么它可以正常工作而没有任何警告,否则,如果x == 2给出以下警告

Warning message:
In if (is.na(d)) { :
  the condition has length > 1 and only the first element will be used
4

2 回答 2

5

无论您的主题行如何,您似乎真的想检查是否d是数据框或其他内容。

if(is.data.frame(d)) {
    # do something sensible with a data frame
}
else print("d is not a data frame!")
于 2013-11-01T02:20:17.557 回答
2

您可以设置dNULL

d <- NULL

然后检查是否is.null(d)

于 2013-11-01T02:21:41.037 回答