首页 > 解决方案 > 如何测试对象是否是R中的向量

问题描述

我想测试一个对象是否是 R 中的一个向量。我很困惑为什么

is.vector(c(0.1))

返回 TRUE,因此也一样

is.vector(0.1)

当它只是一个数字时,我希望它返回 false ,当它是一个向量时返回 true 。任何人都可以提供任何帮助吗?

提前谢谢了。

标签: r

解决方案


在 R 中,不存在单独的数字或字符串。它们是长度为 1 的向量。或者嵌入在一些更复杂的结构中。

is.vector(c(0.1))并且is.vector(0.1)在 R 中是完全一样的。

这也是为什么length("this is a string/character")返回的原因1- 因为length()在这种情况下测量向量中的元素数量。

如果您"this is a string/character"在 R 控制台中输入,您会看到它:它返回[1] "this is a string/character"-[1]指示:长度为 1 的向量。

所以你必须nchar("this is a string/character")得到第一个元素的长度 - 字符字符串 - 返回26

nchar(c("this is a string/character", "and this another string"))
## [1] 26 23
## nchar is vectorized as you see ...

这是与 Python 的一个重要区别,其中字符串和数字可以独立存在。因此len("this")在 Python 中返回 4。len(["this"])但是 1(列表中有 1 个元素,因此列表的长度为 1)。


推荐阅读