Reputation: 701
I am new to programming in R, I am running a loop in R and try to output the result into a dataframe. But I encounter some error I am not able to solve it myself, it would be great if someone can have a look and give me some hints as to how to solve the problem. The process runs until it encounters a "Error" output from one of the loop.
Basically the loop stops producing output to the dataframe and it stops at the point where the loop encounters the error of:
Error in start:end : NA/NaN argument
This is my loop script:
for (i in seq(2,880)){
rscheck<-as.data.frame(cbind(as.matrix(chr1only[,i]), chr1only$SIF1))
rscheck$V2<-as.numeric(as.character(rscheck$V2))
rscheck<-na.omit(rscheck)
pvaluelevenetest2[i-1,1]<-lawstat::levene.test(rscheck$V2, rscheck$V1,correction.method="zero.correction", location="median")$p.value
}
I have the pvaluelenetest2 dataframe contains loop 1 to loop 856 result. But afterward, there is no more result. The dimension of the pvaluelenvenetest2 data is only 1 by 856 (so nothing was returned to the pvaluelentest2 dataframe after the very last non-error test).
I then test the 858th column without using loop and indeed the levene's test produces NA values and gives me this error:
Error in start:end : NA/NaN argument
So I am just wondering is there anyway the loop can continues when it encounters such an error?
thank you
Upvotes: 0
Views: 6100
Reputation: 6365
So your loop is stopping because the levene function is throwing an error. You could write a tryCatch block in R to handle the error:
But wouldn't it be better to to find out why the function is crashing and fix the inputs, or filter out bad inputs to begin with?
For example, add code to check if rscheck$V2 or rscheck$V1 is NA before calling levene. Is it possible that rscheck$V2 contains some characters which can't be converted to numbers, causing the introduction of the NA?
Upvotes: 2