2

当函数不将序列作为参数并且函数使用从函数本身返回的值作为序列的前一个值时,难以在序列上应用函数。

我有以下问题。在我的 main 方法 functionmainn中,我将首先初始化fa, mu.a, mu.b, sigma,然后将其用作函数中的step2参数。(请注意,我很确定我的px.q4和在返回一个值并返回 3 个值step2的意义上工作正常/正确)px.q4step2

这就是我的问题所在。我想step2对一个序列执行应用,并且每次它应用于序列(第一次迭代除外)时,该step2函数将不使用初始值fa.iter,而是使用前一个mu.a.iter,的值。这可以在R中完成吗?还是我必须为这类问题使用 for 循环mu.b.iterstep2

我能够使用 for 循环来做到这一点。但是,我想了解有关 R 的更多信息。是否有一个(更有效的)特定命令可以用来解决这个问题?

#this function returns a value    
px.q4 <- function(fa, mu.a, mu.b,sigma)
{   
  v <- fa + mu.a + mu.b * sigma
  v
}

#this function returns 3 values, fa.iter, mu.a.iter, and mu.b.iter
#for completeness I include the full code of what i am trying to do. 
#But all you need to know is that the function step2 returns 3 values .
step2 <- function(fa, mu.a, mu.b)
{

  #set prev = iter values // this also allow set initial values = prev in 
  #the 1st iteration
  mu.a.prev <- mu.a.iter
  mu.b.prev <- mu.b.iter
  fa.prev <- fa.iter

  #draw a trail point x.trail from propsal distribution ~ N(x_i-1,0.1)
  mu.a.trail <- rnorm(1, mu.a.prev, 0.1)
  mu.b.trail <- rnorm(1, mu.b.prev, 0.1)
  fa.trail <- rnorm(1, fa.prev, 0.1)
  while(fa.trail < 0 || fa.trail > 1)         
  {
    fa.trail <- rnorm(1, fa.prev, sigma)
  }
  #if p(x_trail) >= p(x_i-1) set x_i = x_trail
  a <- px.q4(fa.trail, mu.a.trail, mu.b.trail, sigma) 
  b <- px.q4(fa.prev ,mu.a.prev , mu.b.prev,sigma)
  if(a >= b)
  {
    mu.a.iter <- mu.a.trail
    mu.b.iter <- mu.b.trail
    fa.iter <- fa.trail
  }else{
    r <- runif(1,min = 0, max = 1)
    if(r < a/b){
      mu.a.iter <- mu.a.trail
      mu.b.iter <- mu.b.trail
      fa.iter <- fa.trail
    }else{
      mu.a.iter <- mu.a.prev
      mu.b.iter <- mu.b.prev
      fa.iter <- fa.prev
    }
  }

  res <-  list(mu.a.iter,  mu.b.iter,  fa.iter)
  res
}
#main body

mainn <- function(n,fa,mu.a,mu.b)
{
  sigma <- 0.3
  mu.a.init <- mu.a               #initial values 
  mu.b.init <- mu.b
  fa.init <- fa           #(must be between 0 and 1)

  #set initial values = iter values (for entering for loop)
  mu.a.iter <- mu.a.init
  mu.b.iter <- mu.b.init
  fa.iter <- fa.init

  #where to the logical flaw comes in and how can I overcome it
    y <- sapply(n,FUN = step2)

}
4

1 回答 1

4

您可以使用Reduce在列表上递归地应用函数:例如,

Reduce(`+`, 1:10, accumulate=TRUE)

相当于cumsum(1:10)

在您的情况下,您不是在列表上应用该函数,而只是对其进行迭代:Reduce如果您忽略第二个参数,您仍然可以使用。

# It is easier if your function takes a vector and returns a vector.
# The second argument is ignored.
step2 <- function(x, u) cumsum(x) + rnorm(length(x))
r <- Reduce(step2, 1:100, init=c(0,0,0), accumulate = TRUE)

但是使用循环并没有错:它不应该明显变慢,除非你的函数非常快。

于 2012-11-27T12:28:04.113 回答