r - 如何测试对象是否是R中的向量
问题描述
我想测试一个对象是否是 R 中的一个向量。我很困惑为什么
is.vector(c(0.1))
返回 TRUE,因此也一样
is.vector(0.1)
当它只是一个数字时,我希望它返回 false ,当它是一个向量时返回 true 。任何人都可以提供任何帮助吗?
提前谢谢了。
解决方案
在 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)。
推荐阅读
- android - Adb 如何在不生根模拟图像的情况下解决 DNS 问题?
- javascript - Angular - 在下一个工作流程阶段加载类似的路线不会加载主要对象
- python - 为什么我在使用 python binance 库时会出现此错误?
- node.js - 每次我尝试制作 React 应用程序时,它都在寻找资金并且存在一些漏洞。然后卡住
- android - onChanged LiveData 未调用,RecyclerView 保持为空
- r - 如何使用 ggplot2 为散点图绘制多条趋势线?
- c# - C# WPF Websocket - 无法与 NGINX 建立握手
- javascript - 从间隔内更改 setInterval 时间
- reactjs - Rxjs observable 被订阅了两次
- python - 带有循环的“列表索引超出范围”