如何测试对象是否为向量 [英] How to test if object is a vector
问题描述
如何测试一个对象是否为向量,即模式logical
、numeric
、complex
或character
?is.vector
的问题在于它还会为列表和其他类型返回 TRUE
:
How to test if an object is a vector, i.e. mode logical
, numeric
, complex
or character
? The problem with is.vector
is that it also returns TRUE
for lists and perhaps other types:
> is.vector(list())
[1] TRUE
我想知道它是否是原始类型的向量.是否有本机方法,还是必须使用存储模式?
I want to know if it is a vector of primitive types. Is there a native method for this, or do I have to go by storage mode?
推荐答案
只有原始函数,所以我假设您想知道向量是否是原子类型之一.如果你想知道一个对象是否是原子的,使用 is.atomic
.
There are only primitive functions, so I assume you want to know if the vector is one of the atomic types. If you want to know if an object is atomic, use is.atomic
.
is.atomic(logical())
is.atomic(integer())
is.atomic(numeric())
is.atomic(complex())
is.atomic(character())
is.atomic(raw())
is.atomic(NULL)
is.atomic(list()) # is.vector==TRUE
is.atomic(expression()) # is.vector==TRUE
is.atomic(pairlist()) # potential "gotcha": pairlist() returns NULL
is.atomic(pairlist(1)) # is.vector==FALSE
如果您只对您提到的原子类型的子集感兴趣,最好明确测试它们:
If you're only interested in the subset of the atomic types that you mention, it would be better to test for them explicitly:
mode(foo) %in% c("logical","numeric","complex","character")
这篇关于如何测试对象是否为向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!