R 函数调用,...和缺失值
R function calls, ... and missing values
我正在尝试在 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)
}
哪里
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]
替换 ...
中缺少的参数,最好的方法是什么?也欢迎其他解决方案!
这里有一个方法可以解决这个问题:
#
isEmptySymbol <- function(x) is.symbol(x) && identical("", as.character(x))
foo <- function(...) {
i <- as.list(match.call())[-1] #call before evaluation
#replace empty symbols (here with 0 as an example)
i[vapply(i, isEmptySymbol, FUN.VALUE = TRUE)] <- 0
#evaluate all list elements
lapply(i, eval)
}
x <- 2
foo(1, , x)
#[[1]]
#[1] 1
#
#[[2]]
#[1] 0
#
#[[3]]
#[1] 2
我正在尝试在 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)
}
哪里
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]
替换 ...
中缺少的参数,最好的方法是什么?也欢迎其他解决方案!
这里有一个方法可以解决这个问题:
#
isEmptySymbol <- function(x) is.symbol(x) && identical("", as.character(x))
foo <- function(...) {
i <- as.list(match.call())[-1] #call before evaluation
#replace empty symbols (here with 0 as an example)
i[vapply(i, isEmptySymbol, FUN.VALUE = TRUE)] <- 0
#evaluate all list elements
lapply(i, eval)
}
x <- 2
foo(1, , x)
#[[1]]
#[1] 1
#
#[[2]]
#[1] 0
#
#[[3]]
#[1] 2