我正在尝试在R中实现自己的数组类型,并希望其语义与内置数组匹配。为此,我必须能够处理以下呼叫:
my.array(1:9, c(3, 3, 3))
x[1:2, 1, 2]
x[,,3]
我将其实现为:
`[.my.array` <- function(x, ..., drop = TRUE) {
os <- range_to_offset_shape(...)
result <- getindex(x, offset = os$offset, shape = os$shape)
if(drop) result <- handle_drop(result)
return(result)
}
where
range_to_offset_shape <- function(...) {
i <- list(...)
offset <- sapply(i, function(x) x[1])
shape <- sapply(i, function(x) x[length(x)] - x[1] + 1)
return(list(offset = offset, shape = shape))
}
只要没有遗漏的论点,就可以了。为了使这项工作有效,我必须用...
替换1:dim(x)[i]
中缺少的参数,什么是最好的方法?也欢迎其他解决方案!
这里有可能解决这个问题: