dim() 外部错误

dim() Error in outer

我制作了以下函数我想制作一个使用函数"persp"的3维图像,因此我使用函数outer,来获取a的每个组合的函数值和 b,但这会出错。

所以我的代码是:

a<- seq(from=0, to=5,by=0.25)
b<- seq(from=0.1, to=2,by=0.1)

Rab <- function(a,b){
  r <- matrix(ncol = 1, nrow = 4)
  for (p in seq(from=0, to=4,by=1)){
  g <- ifelse(a>=0 & a<1-1/p & p >b, a*p,
         ifelse(a>=0 & a<1-1/b & p< b, -1+(a+1/b),
                ifelse(a > 1-1/max(p,b),-1+p,NA)))
  w <- p
  r[w] <- g
  }
  return(r)
} 

q <- outer(a,b,Rab)

然后我收到以下错误和警告消息,我不明白。

Error in outer(a, b, Rab) : 
  dims [product 420] do not match the length of object [4]
In addition: Warning messages:
1: In r[w] <- g :
  number of items to replace is not a multiple of replacement length
2: In r[w] <- g :
  number of items to replace is not a multiple of replacement length
3: In r[w] <- g :
  number of items to replace is not a multiple of replacement length
4: In r[w] <- g :
  number of items to replace is not a multiple of replacement length

我已经尝试阅读它,我认为是因为我将函数 Rab 构造错了,但我不知道如何更正它。

感谢任何帮助。

你是对的,你的 Rab 函数是错误的。 outer 的文档说

X and Y must be suitable arguments for FUN. Each will be extended by rep to length the products of the lengths of X and Y before FUN is called.

FUN is called with these two extended vectors as arguments (plus any arguments in ...). It must be a vectorized function (or the name of one) expecting at least two arguments and returning a value with the same length as the first (and the second).

所以在你的例子中 ab 都被扩展到长度 length(a) * length(b),在你的例子中恰好是 420。你的函数 Rab 应该 return 一个相同长度的向量。

Rab 中,您计算​​一个向量 g,它具有正确的长度并且适合作为 return 值。您尝试将它分配给矩阵 r 中的一个条目,而不是 returning 这个向量。请注意,此矩阵定义为

r <- matrix(ncol = 1, nrow = 4)

并且不能在其行或列中包含长度为 420 的向量(这是警告消息的内容)。在此过程中,除了矢量 g 的第一个元素外,您将丢失所有元素。然后您继续使用一组略有不同的参数重新计算 g,这将我们带到下一个问题。这些计算发生在一个定义如下的循环中:

for (p in seq(from=0, to=4,by=1)){
  ## compute g ...
  r[p] <- g
}

你似乎期望这个循环被执行四次,但实际上它是 运行 五次,因为 p 的值等于 0、1、2、3 和 4。这意味着首先 g 分配给 r[0],R 默默地忽略它。当然,当您随后尝试 return r none 时,这确实很重要,因为它的长度只有 4(而不是 420),这会触发错误。

我不相信我真的理解你正在尝试做什么,但以下可能是朝着正确方向迈出的一步。

Rab <- function(a, b, p){
  ifelse(a>=0 & a<1-1/p & p >b, a*p,
                 ifelse(a>=0 & a<1-1/b & p< b, -1+(a+1/b),
                        ifelse(a > 1-1/max(p,b),-1+p,NA)))
}

这将从您的函数计算一次 g 的固定值 p 和 return 结果。你可以这样称呼它(对于 p=0):

q <- outer(a, b, Rab, 0)

如果你想为多个不同的 p 调用它,你可以这样做

q <- lapply(0:3, function(x,y,f, p) outer(x, y, f, p), x=a, y=b, f=Rab)

这将调用 Rab,p = 0、1、2 和 3(我猜这就是您想要的,根据需要进行调整)。