R - 循环期间的闭包子集错误

时间:2017-01-18 12:00:57

标签: r dataframe closures

我有以下代码来计算矩阵 raw 中ts数据的ADF统计数据。

raw <- matrix(rnorm(25000), nrow=1000,ncol=25)
for (i in 1:(ncol(raw)-1)) {
    for (j in (i+1):ncol(raw)) {

        df <- data.frame(N = integer(0), DFStat = numeric(0), PVAL =     numeric(0))
        name <- paste(i,j, sep="_")
        dir <- paste("C:/Data/rOUT/", name,".txt",sep="")
        for (t in 1:20) {
             N <- 50*t
             xtail <- tail(raw[,i],N)
             ytail <- tail(raw[,j],N)
             reg <- lm(ytail ~ xtail)
             test <- adf.test(reg$residuals, k = 1)
             df[t,] <- c(N, test$statistic, test$p.value)
             write.table(df, dir, sep="\t", row.names=FALSE)
             rm(df)

        }
    }
}

前两个循环中的块在没有循环遍历raw的列时运行完美,但是当我尝试遍历raw时,我得到下面的闭包错误:

Error in df[t, ] <- c(N, test$statistic, test$p.value) : 
  object of type 'closure' is not subsettable

有谁知道为什么我遇到这种差异以及我可以采取的纠正措施?

1 个答案:

答案 0 :(得分:1)

我猜你的rm(df)处于错误的位置。运行以下代码:

raw <- matrix(rnorm(250), nrow=10,ncol=25)
for (i in 1:(ncol(raw)-1)) {
  for (j in (i+1):ncol(raw)) {

    df <- data.frame(N = integer(0), DFStat = numeric(0), PVAL =     numeric(0))
    name <- paste(i,j, sep="_")
    dir <- paste("C:/Data/rOUT/", name,".txt",sep="")
    for (t in 1:20) {
      N <- 50*t
      xtail <- tail(raw[,i],N)
      ytail <- tail(raw[,j],N)
      reg <- lm(ytail ~ xtail)
      # test <- adf.test(reg$residuals, k = 1)
      # df[t,] <- c(N, test$statistic, test$p.value)
      df[t,] <- c(N, 1, 1)
      # write.table(df, dir, sep="\t", row.names=FALSE)


    }
    rm(df)
  }
}