inconsistency in a for loop with lists

时间:2018-05-06 17:05:03

标签: r debugging

I have downloaded the historical stock prices of a list of 218 stocks. I want check whether it is populated with the the most recent date or not. I have written a function to that effect, by name familyName

font

snlq is list of stocks with length 218 and of class check.date

But when I run it, I get the following output:

function(snlq){
     j <- 1;
     for(i in 1:length(snlq)){
         ind <- index(snlq[[i]])
         if(identical(ind[length(ind)],"2018-05-04") == FALSE){
                  s[j] <- i
                  j <- j+1
         }
      }
      return(s);
}

How can the output be of length more than 218? Also I have checked that snlq[[1]] is up to date; then why is 1 in the output?

This might seem like a simple for loop problem, but is perplexing me.

Very many thanks for your time and effort...

2 个答案:

答案 0 :(得分:1)

问题似乎是s未在更新和使用它的scope中创建。 @ Dave2e在上面的评论中正确指出了。在我看来,最合乎逻辑的错误是在s空间中创建了global,这就是为什么你的函数没有给出错误,否则你的函数就不会运行。

有很多方法可以解决这个问题。其中一个选项可以是:

check.date <- function(snlq){
  j <- 1;
  ss <- integer()  #declare before use in function scope
  for(i in 1:length(snlq)){
    ind <- index(snlq[[i]])
    if(identical(ind[length(ind)],"2018-05-04") == FALSE){
      s = c(s,j)  #Kind of adding an element to vector s
      j <- j+1
    }
  }
  return(s);
}

答案 1 :(得分:0)

如果没有可重复的示例,我无法检查此结果,但我认为这将极大地简化您的功能。

check.data <- function(input, today) {
  result <- sapply(input, function(x) {
    ind <- index(x)
    !identical(ind[length(ind)], today)
  })

  which(result)
}