首页 > 解决方案 > R使用小数作为索引号

问题描述

R 文档说:

索引是数字或字符向量或空(缺失)或 NULL。数值被 as.integer 强制转换为整数(因此被截断为零)。

例如,如果您有:

vector<-c(10,20,30,40,50)

并询问该向量的位置 2,您将拥有:

vector[2];
20

但是,如果您要求索引 2.5,您可以获得相同的结果

vector[2.5];
20

这是一个非常奇怪的行为。就我的目的而言,这是一种危险的行为。当您将十进制值作为数组或向量索引时,是否可以强制 R 返回错误?

标签: rindexingdecimal

解决方案


一种可能性是定义具有所描述行为的向量类:

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

推荐阅读