如何测试对象是否为向量

时间:2022-07-10 17:00:11

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的问题是它也为列表和其他类型返回TRUE:

> 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?

我想知道它是否是原始类型的向量。是否有本机方法,或者我必须通过存储模式?

2 个解决方案

#1


22  

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。

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")

#2


4  

Perhaps not the optimal, but it will do the work: check if the variable is a vector AND if it's not a list. Then you'll bypass the is.vector result:

也许不是最优的,但它会完成工作:检查变量是否是向量,如果它不是列表。然后你将绕过is.vector结果:

if(is.vector(someVector) & !is.list(someVector)) { 
  do something with the vector 
}

#1


22  

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。

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")

#2


4  

Perhaps not the optimal, but it will do the work: check if the variable is a vector AND if it's not a list. Then you'll bypass the is.vector result:

也许不是最优的,但它会完成工作:检查变量是否是向量,如果它不是列表。然后你将绕过is.vector结果:

if(is.vector(someVector) & !is.list(someVector)) { 
  do something with the vector 
}