R函数调用。。。和缺少的值

R函数调用。。。和缺少的值,r,arrays,variadic-functions,R,Arrays,Variadic Functions,我试图在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

我试图在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)
}

`[.my.array`这里有一种可能性:

#https://stackoverflow.com/a/20906150/1412059
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
#https://stackoverflow.com/a/20906150/1412059

isEmptySymbol您的函数应该有参数
i
j
。然后您可以执行
if(missing(i)){…}
。使用
[.data.frame
作为指导原则。问题是数组的维数可能是可变的,然后检查
i
列表是否有任何空元素。调用
list(…)
如果缺少元素,则会产生错误。对于样式点:如果您希望
由另一个函数处理,则此操作无效,例如
bar Can't you do
do.call(baz,foo(…)
?问题是在
foo
中,符号名称更改为
.1
.2
。。。
#https://stackoverflow.com/a/20906150/1412059
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