r - R使用小数作为索引号
问题描述
R 文档说:
索引是数字或字符向量或空(缺失)或 NULL。数值被 as.integer 强制转换为整数(因此被截断为零)。
例如,如果您有:
vector<-c(10,20,30,40,50)
并询问该向量的位置 2,您将拥有:
vector[2];
20
但是,如果您要求索引 2.5,您可以获得相同的结果
vector[2.5];
20
这是一个非常奇怪的行为。就我的目的而言,这是一种危险的行为。当您将十进制值作为数组或向量索引时,是否可以强制 R 返回错误?
解决方案
一种可能性是定义具有所描述行为的向量类:
as.myvector <- function(x){
class(x) <- c("myvector", class(x))
x
}
`[.myvector` <- function(x, condition) {
if(any(condition != as.integer(condition)))
stop("Invalid index")
class(x) <- class(x)[2]
x[condition]
}
v <- as.myvector(c(10, 20, 30, 40, 50))
v[2]
## [1] 20
v[2.5]
## Error in `[.myvector`(v, 2.5) (from #2) : Invalid index
v[2:5]
## [1] 20 30 40 50
v[c(1.1,2:4)]
## Error in `[.myvector`(v, c(1.1, 2:4)) (from #2) : Invalid index
推荐阅读
- android-studio - 从片段更改活动的按钮状态
- pine-script - 如何计算 TradingView 中经济指标/数据集的净变化?
- html - 如何阻止标题与导航重叠?
- sql-server - 从不同服务运行 UPDATE 和 INSERT 查询时的性能问题
- macos - 在 Safari 中打开新标签的终端命令
- elasticsearch - Elastic Filebeat 不会使用映射将自定义索引编入索引
- python - 如何使用自定义测试填充 gnome-builder 中的单元测试字段?
- javascript - 循环遍历 JSON 数据并动态显示它们
- logic - 什么是“可计算函数的逻辑”?
- u-boot - U-boot 源码中的 eth_device 结构处理