R中NULL和character(0)有什么区别?
NULL 和字符(0) 有什么区别 |整数(0)等?
> identical(NULL, character(0))
[1] FALSE
> is.null(integer(0))
[1] FALSE
> str(character(0))
chr(0)
> str(NULL)
NULL
一般来说,您似乎可以将 NULL
作为参数传递给函数,并且空向量通常以 character(0)
、integer(0)
形式返回code>等等
为什么会这样呢?想一想,是否有一个零度测试,a la is.integer0
?
What is the difference between NULL and character(0) | integer(0) etc?
> identical(NULL, character(0))
[1] FALSE
> is.null(integer(0))
[1] FALSE
> str(character(0))
chr(0)
> str(NULL)
NULL
In general it seems you can pass NULL
as parameters into functions, and that an empty vector is generally returned as character(0)
, integer(0)
, etc.
Why is this the case? Come to think of it, is there a test for zero-ness, a la is.integer0
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
R 语言定义n 在
NULL< 上有此内容/代码>:
因此,根据定义,
NULL
与零长度向量非常不同。零长度向量并不不存在。NULL
实际上是对缺失或未设置的内容的包罗万象,但不是缺失,这是NA
的工作。有一个例外,即零长度对列表,正如 @Owen 提到的。语言定义指出:这突出了本例中的例外情况。
要测试零长度向量,请使用类似
if(length(foo) == 0L)
的内容。如果您想要特定类型的零长度向量,请将其与类检查 (is.character(foo)
) 结合起来。The R Language Definition has this on
NULL
:So by definition
NULL
is very different to zero length vectors. A zero length vector very much isn't absent.NULL
is really a catch-all for something that is absent or not set, but not missing-ness, which is the job ofNA
. There is an exception, the zero-length pairlist, as mentioned by @Owen. The Language Definition states:which highlights the exception in this case.
To test for a zero-length vector use something like
if(length(foo) == 0L)
for example. And combine that with a class check (is.character(foo)
) if you want a specific type of zero length vector.其他人有正确的答案,但我想补充一些好奇心。
首先,正如文档中所说,NULL“在需要指示或指定对象不存在时使用”并不完全正确。 R 中实际上还有另外 2 个“无数据”值(不包括 NA,这不是一个完整的值)。
有“missing”,用于缺少参数:
然后是“unbound”,你不能(据我所知)直接访问它,但可以使用 C:
The other guys have the right answers, but I want to add a few curiosities.
First, it's not quite true that NULL "is used whenever there is a need to indicate or specify that an object is absent" as it says in the doc. There are actually 2 other "no data" values in R (not counting NA, which is not a complete value).
There's "missing", which is used for missing arguments:
Then there's "unbound", which you can't (AFAIK) access directly, but using C:
这是部分答案,首先简单引用 R 语言定义指南:
我认为这意味着零长度向量可以具有属性,而
NULL
不能:Here's a partial answer, beginning by simply quoting the R Language Definition Guide:
I take that to mean that zero length vectors can have attributes, whereas
NULL
cannot: