-1

I am doing some processing and this is my code

wrongDateValues <- function(date){
    wrongIndexes <- c()
    wrongValues <- c()
    for(value in date){
      formattedDate <- strptime(value, "%Y%m%d")
      if(is.na(formattedDate)){
        wrongValues <- c(wrongValues, value)
        wrongIndexes <- c(wrongIndexes, value)
      }
    }
    wrongResults <- matrix(c(wrongValues, wrongIndexes), byrow = FALSE, ncol = 2)
    colnames(wrongResults) <- c("WrongValues", "WrongIndexes")
    return (wrongResults)
}

as you see, now in the wrongIndexes i am saving the values, because ** i don't know how to save the index**

could you help?

Paolo RLang
  • 1,654
  • 2
  • 11
  • 10
  • It is very unclear to me what you are trying to do. Please make a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Provide some sample input and describe the desired output for your function. – MrFlick May 23 '15 at 18:31
  • @MrFlick i am trying to do some checks for the values. However, my question has another to do with my purpose. I just need to know how to get the index inside the for loop. did you get me please? if not , i can describe more – Paolo RLang May 23 '15 at 18:33
  • `for(index in seq_along(date))` – Neal Fultz May 23 '15 at 18:33
  • @NealFultz do you imply that after using your code, the `value` variable will be `data[index]` ? – Paolo RLang May 23 '15 at 18:35
  • Yes, that sounds correct. – Neal Fultz May 23 '15 at 18:36

1 Answers1

1

It seems like you are just trying to find non-date values in a vector. There are better ways to do with without a for loop

wrongDateValues<-function(x) {
    dt<-strptime(x, "%Y%m%d")
    bad<-which(is.na(dt))
    data.frame(WrongValues = x[bad], WrongIndexes=bad)
}
x<-c("20010605", "20120420","bad","20150101")
wrongDateValues(x)

In a for loop, you only have access to the values you are iterating over, you do not have access to the current index. If you need the current index, you would need to iterate over that rather than the values themselves.

MrFlick
  • 195,160
  • 17
  • 277
  • 295