0

我正在尝试使用 mapply 函数创建等高线图。我是 R 的新手,我已经阅读了其他关于 mapply 的帖子,但我仍然没有得到 mapply 函数的精髓。我陷入了以下问题。

我有一个返回值的函数 px (它接受 2 个参数)。我正在尝试使用 draw.graph 函数制作等高线图,该函数将接收 2 个序列 (n1,n2) 作为参数。但是,我一直收到一个错误,说 contour() 中的 z 不是矩阵。

我尝试使用 browser() 并意识到在执行 mapply() 之后,我没有得到一个矩阵。所以我的问题是如何在这种情况下使用 mapply 函数获取矩阵???如果可能的话,有人能指出我在代码中犯的错误吗?我不断收到以下错误:

 Error in contour.default(n1, n2, y) : no proper 'z' matrix specified

    # This function returns a value only    
        px <- function(mu.a, mu.b)
            {
                   #Note that x is just a vector in this context. specified
                   # outside the function. Since it is very long, I want specify it here.           
                    n1 <- dnorm(x, mean = mu.a, sd = 0.3)
                n2 <- dnorm(x, mean = mu.b, sd = 0.3)

                pxd<- 0.7 * n1 + (1-0.7) * n2

                return
                {
                    prod(pxd)
                }   
            } 
            #I am trying to generate a contour plot below of the function px.q3 with
           # arguments n1,n2, which will be sequences
            draw.graph <- function(n1,n2)
            {   

                y <- mapply(px,n1,n2)
                browser()
                contour(n1,n2,y)
            }
            draw.graph(seq(1.0,1.6,0.01),seq(2.4,3,0.01))

My aim of the draw.graph function is to get a contour plot as a function mu.a(i.e. n1) and mu.b(i.e. n2) <- 2 sequences. 
4

2 回答 2

3

您没有将 x 的任何值传递给此函数...我假设您使用的是全局的???淘气!

你可以像这样让 px 变得有趣

px <- function(mu.a, mu.b, x)
        { etc..

然后您可以使用MoreArgs选项指定 x

y2 <- mapply(FUN=px,n1,n2, MoreArgs=list(x), SIMPLIFY = T)

y2 是一个向量而不是你需要重塑的矩阵

dim(y2)=c(length(n2), length(n1))
于 2012-11-26T19:28:51.427 回答
1

在这里,您可以使用outer()而不是使用mapply( ) .. 而不是分段执行所有组合,这就是我认为您想要的?注意使用Vectorize()创建一个向量化函数,该函数接受mu.amu.b作为向量,而x对于所有组合都是固定的。

这下面肯定有效(即产生一个工作图),但我不确定它应该看起来像那样???

x1 = seq(0, 1,.1)
n1=seq(1.0,1.6,0.01)
n2=seq(2.4,3,0.01)

#question 3 - as a function mu.a, mu.b
px.q3 <- function(mu.a, mu.b, x=x1)
{
  n1 <- dnorm(x, mean = mu.a, sd = 0.3)
  n2 <- dnorm(x, mean = mu.b, sd = 0.3)
  #p(x_d)
  pxd<- 0.7 * n1 + (1-0.7) * n2

  return
  {
  prod(pxd)
  }   
}

vectorised.px.q3=Vectorize(px.q3)
y= outer(n1,n2, FUN=vectorised.px.q3)
contour(n1,n2,y)
于 2012-11-26T23:55:42.617 回答