避免R函数中的循环

时间:2014-01-30 20:26:15

标签: r performance loops vectorization

我正在编写一个R包,它在其中一个函数中使用以下代码

这里我加载数据

指向数据的链接如下

https://www.dropbox.com/s/rrh4c1sn96ja7wp/PIBcol_SD.txt

   info   <-  read.table("./Datos/PIBcol_SD.txt",header=TRUE,row.names=1,dec=".")
   attach     (info)

   lpib      <-  ts   (log(PIB) , start= c(1982,1)  , frequency = 4)
   series     <-  diff (lpib     , lag=4)
   trans     <-  lag   (series    , k=-1)

   linear    <- c(1,4)
   nonlinear <- 1

这是函数启动的地方

  linear <- c (0,linear)
  nonlinear <- c (0,nonlinear)

  linear_list           <- lapply (linear, function(i) lag(series, k=-i))
  linear_dat            <- na.omit(do.call(cbind, linear_list))
  colnames(linear_dat)  <- paste0 ("lag_",linear)

  nonlinear_list           <- lapply (nonlinear, function(i) lag(series, k=-i))
  nonlinear_dat            <- do.call(cbind, nonlinear_list)
  colnames(nonlinear_dat)  <- paste0 ("nl.lag_",nonlinear)  
  nonlinear_dat            <- window (nonlinear_dat, start=start(linear_dat),end=end(linear_dat))

  trans       <- window (trans, start=start(linear_dat),end=end(linear_dat))
  scale       <- sqrt   (var(trans))
  grid        <- list()


    for (c1 in seq(min(trans), max(trans), mean(trans)/20)){
      for (gamma in seq(1,100,0.5))                                    {

    transition  <- (1+exp(-(gamma/scale)*(trans-c1)))^-1

    lin_eq                <- paste0("lag_0 ~",  paste(paste(colnames(linear_dat)[-1]), sep="",collapse='+'))      
    nonlin_eq             <- paste0("transition + ",paste("I(transition*",paste(colnames(nonlinear_dat)[-1],")"), sep="",collapse='+'))

    grid.regre <-lm(paste0(lin_eq,"+",nonlin_eq),data=data.frame(linear_dat,nonlinear_dat,trans)) 

    coef  <- grid.regre$coefficients
    RSS   <- sum(grid.regre$residuals^2)
    grid[[length(grid)+1]] <- c(RSS,gamma,c1,coef)  
  } 
}

Small_RSS         <- which.min(sapply(grid, "[[", 1))  
Start_val         <- grid[[Small_RSS]]
names(Start_val)  <- c("RSS","gamma","c1",c("intercept",colnames(linear_dat)[-1],"nl_intercept",colnames(nonlinear_dat)[-1]))

Start_val 

当我包含一些其他参数(如c1)时,迭代似乎永远需要。在之前的帖子中有人告诉我,有一种方法可以避免做循环(也许使用expand.grid)。我试图这样做不成功。

你能帮我吗?

提前致谢!

0 个答案:

没有答案