代码适用于单次运行,但不适用于循环(for-loop)

时间:2014-04-09 18:54:22

标签: r for-loop matrix

我需要一个非常擅长分析代码的人! 我已经得到了这个"难以解释的 - 我想要做什么和难以制作的可复制的例子" - 代码片段。但是有可能分析和比较两个代码块并告诉我们哪里出错了。对于循环,出现错误:

 Error in max(i) : (converted from warning) no non-missing arguments to max; returning -Inf

我想弄清楚为什么for循环不起作用,所以我为一次运行(第一个块)编写了代码..它的工作原理!这两段代码完全相同,只是一个是循环而另一个不是。我做错了什么?

# here I'm just creating some important Objects
permnos <- as.vector(unique(data$PERMNO)) # all Firms in data
days <- as.vector(unique(data$DATE)) # all trading days
W <- as.data.frame(lag(zoo(days), -c(0, 250:1))) # time window auxiliary object
mylist <- vector('list', length(permnos))

没有循环的第一个块:

# FOR ONE COMPANY (PERMNO) EVERYTHING WORKS PERFECTLY
# for{g} 
data_g <- data[data$PERMNO %in% "10104",] # choosing one random company (always one company is chosen for each loop)
events_g <- events[events$PERMNO %in% "10104",] # choosing one random company

# for{u} 
date_u <- "03.10.2005" # choosing one random date (always one date is chosen for each loop)
z = W[W[,1] == date_u, ] # time window of all 251 trading days before event day
r <- data_g[which(is.na(match(z, data_g[["DATE"]]) == F)), "RET"] # 251 returns of time window days 

y <- as.matrix(as.numeric(r) - as.numeric(ff[which(is.na(match(z, ff[["DATE"]]) == F)), "RF"])) # Excess Return (y is matrix with one column of length 251)
x = as.matrix(ff[which(is.na(match(z, ff[["DATE"]]) == F)), c("Mkt.RF", "SMB", "HML")]) # factors (x is matrix with 3 columns of length 251)

p = solve((t(x)%*%x), (t(x)%*%y)) # OLS Regression using matrices

events_g[events_g$DATE %in% date_u, "AR"] = as.numeric(data_g[data_g$DATE %in% date_u, "RET"]) - p[1:3] %*% as.numeric(ff[ff$DATE %in% date_u,1:3]) # 

带循环的第二个块:

# FOR ALL COMPANIES (IN THE LOOP) IT DOESN'T WORK
for(i in 1:length(permnos)) {
  permno_i <- permnos[i]
  data_k <- data[which(data$PERMNO==permno_i), ] # all trading days of one firm
  events_k <- events[which(events$PERMNO==permno_i), ] # all event day of one firm 

  for(j in 1:nrow(events_k)) { 
    date_j = events_k[j, "DATE"] 
    Z = W[W[,1] == date_j, ] 
    R = data_k[which(is.na(match(Z, data_k[["DATE"]]) == F)), "RET"]

    Y = as.matrix(as.numeric(R) - as.numeric(ff[which(is.na(match(Z, ff[["DATE"]]) == F)), "RF"]))
    X = as.matrix(ff[which(is.na(match(Z, ff[["DATE"]]) == F)), c("Mkt.RF", "SMB", "HML")]) # war ff[,"DATE"]

    b = solve((t(X)%*%X), (t(X)%*%Y)) # OLS

    events_k[events_k$DATE %in% date_j, "AR"] = as.numeric(data_g[data_g$DATE %in% date_j, "RET"]) 
    - b[1:3] %*% as.numeric(ff[ff$DATE %in% date_j,1:3]) # 

    } 
  mylist[[i]] = events_k[,"AR"] 

  } 

myvector <- unlist(ES_list) 

我不明白为什么max(i)出现错误,我不明白为什么循环中出现错误,即使代码适用于一次运行。 任何人都可以帮我这个吗?

0 个答案:

没有答案