R文件说:
索引是数字或字符向量或空(缺失)或NULL。与as.integer一样,数值被强制为整数(因此被截断为零)。
例如,如果您有:
vector<-c(10,20,30,40,50)如果问到这个向量的位置2,你就会有:
vector[2];
20但是,如果请求索引2.5,则可以得到相同的结果
vector[2.5];
20这是一种非常奇怪的行为。对我来说,这是一种危险的行为。当您将十进制值作为数组或向量索引时,是否有强制R返回错误的选项?
发布于 2018-10-23 15:53:44
一种可能是使用描述的行为定义向量类:
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 indexhttps://stackoverflow.com/questions/52951998
复制相似问题