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
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:
How to write trycatch in R
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?
Related
I got the error message:
Error: object 'x' not found
Or a more complex version like
Error in mean(x) :
error in evaluating the argument 'x' in selecting a method for function 'mean': Error: object 'x' not found
What does this mean?
The error means that R could not find the variable mentioned in the error message.
The easiest way to reproduce the error is to type the name of a variable that doesn't exist. (If you've defined x already, use a different variable name.)
x
## Error: object 'x' not found
The more complex version of the error has the same cause: calling a function when x does not exist.
mean(x)
## Error in mean(x) :
## error in evaluating the argument 'x' in selecting a method for function 'mean': Error: object 'x' not found
Once the variable has been defined, the error will not occur.
x <- 1:5
x
## [1] 1 2 3 4 5
mean(x)
## [1] 3
You can check to see if a variable exists using ls or exists.
ls() # lists all the variables that have been defined
exists("x") # returns TRUE or FALSE, depending upon whether x has been defined.
Errors like this can occur when you are using non-standard evaluation. For example, when using subset, the error will occur if a column name is not present in the data frame to subset.
d <- data.frame(a = rnorm(5))
subset(d, b > 0)
## Error in eval(expr, envir, enclos) : object 'b' not found
The error can also occur if you use custom evaluation.
get("var", "package:stats") #returns the var function
get("var", "package:utils")
## Error in get("var", "package:utils") : object 'var' not found
In the second case, the var function cannot be found when R looks in the utils package's environment because utils is further down the search list than stats.
In more advanced use cases, you may wish to read:
The Scope section of the CRAN manual Intro to R and demo(scoping)
The Non-standard evaluation chapter of Advanced R
While executing multiple lines of code in R, you need to first select all the lines of code and then click on "Run".
This error usually comes up when we don't select our statements and click on "Run".
Let's discuss why an "object not found" error can be thrown in R in addition to explaining what it means. What it means (to many) is obvious: the variable in question, at least according to the R interpreter, has not yet been defined, but if you see your object in your code there can be multiple reasons for why this is happening:
check syntax of your declarations. If you mis-typed even one letter or used upper case instead of lower case in a later calling statement, then it won't match your original declaration and this error will occur.
Are you getting this error in a notebook or markdown document? You may simply need to re-run an earlier cell that has your declarations before running the current cell where you are calling the variable.
Are you trying to knit your R document and the variable works find when you run the cells but not when you knit the cells? If so - then you want to examine the snippet I am providing below for a possible side effect that triggers this error:
{r sourceDataProb1, echo=F, eval=F}
# some code here
The above snippet is from the beginning of an R markdown cell. If eval and echo are both set to False this can trigger an error when you try to knit the document. To clarify. I had a use case where I had left these flags as False because I thought i did not want my code echoed or its results to show in the markdown HTML I was generating. But since the variable was then used in later cells, this caused an error during knitting. Simple trial and error with T/F TRUE/FALSE flags can establish if this is the source of your error when it occurs in knitting an R markdown document from RStudio.
Lastly: did you remove the variable or clear it from memory after declaring it?
rm() removes the variable
hitting the broom icon in the evironment window of RStudio clearls everything in the current working environment
ls() can help you see what is active right now to look for a missing declaration.
exists("x") - as mentioned by another poster, can help you test a specific value in an environment with a very lengthy list of active variables
I had a similar problem with R-studio. When I tried to do my plots, this message was showing up.
Eventually I realised that the reason behind this was that my "window" for the plots was too small, and I had to make it bigger to "fit" all the plots inside!
Hope to help
I'm going to add this on here even though it's not a new question as it comes quite highly in the search results for the error:
As mentioned above, re checking syntax, if you're using dplyr, make sure you have all the %>% pipes at the end of the lines above the error, otherwise the contents of anything like a select statement won't pass down into the next part of the code block.
I am running a simulation study in R. Occassionally, my simulation study produces an error message. As I implemented my simulation study in a function, the simulation stops when this error message occurs. I know that it is bad practice to suppress errors, but at this moment to me there is no other option than to suppress the error and then go on with the next simulation until the total number of simulations I like to run. To do this, I have to suppress the error message R produces.
To do this, I tried different things:
library(base64)
suppressWarnings
suppressMessages
options(error = expression(NULL))
In the first two options, only warnings and message are suprressed, so that's no help. If I understand it correctly, in the last case, all error messages should be avoided. However, that does not help, the function still stops with an error message.
Has someone any idea why this does not work the way I expect it to work? I searched the internet for solutions, but could only find the above mentioned ways.
In the function I am running my simulation, a part of the code is analysed by the external program JAGS (Gibbs sampler) and the error message is produced by this analysis. Might this be where it goes wrong?
Note that I do not have to supress a certain/specific error message, as there are no other error messages produced, it is 'good enough' to have an option that supresses just all error messages.
Thanks for your time and help!
As suggested by the previous solution, you can use try or tryCatch functions, which will encapsulate the error (more info in Advanced R). However, they will not suppress the error reporting message to stderr by default.
This can be achieved by setting their parameters. For try, set silent=TRUE. For tryCatch set error=function(e){}.
Examples:
o <- try(1 + "a")
> Error in 1 + "a" : non-numeric argument to binary operator
o <- try(1 + "a", silent=TRUE) # no error printed
o <- tryCatch(1 + "a")
> Error in 1 + "a" : non-numeric argument to binary operator
o <- tryCatch(1 + "a", error=function(e){})
There is a big difference between suppressing a message and suppressing the response to an error. If a function cannot complete its task, it will of necessity return an error (although some functions have a command-line argument to take some other action in case of error). What you need, as Zoonekynd suggested, is to use try or trycatch to "encapsulate" the error so that your main program flow can continue even when the function fails.
I met a pretty strange error in R. When I tried to display a list returned by lapply, the following error message was showed:
Error in if (n <= 1L || lenl[n] <= width) n else max(1L, which.max(lenl > :
missing value where TRUE/FALSE needed
The if... in the error message was not written by me, I think it is some inner function of R.
The code I wrote looks like the following (flags is a dataframe)
The first statement was executed successfully, the error only appeared when I tried to display unique_vals by running the second statement.
Can anyone tell me how to fix it?
I have tried to change the font of the console to the smallest, as well as use na.omit() to delete the missing values in the list, but none of them worked. I am extremely confused about why simply displaying a list will incur such as error, which I have never encountered before.
unique_vals<-lapply(flags,unique)
unique_vals
I am new to R, and learning it online by trying out some simple code
I read try() allows to ignore any error and continue. So I tried this:
When I put log() inside try(), I was still getting the same output;
I was expecting something like:
Error in log(x) : non-numeric argument to mathematical function
[1] 10
But that 10 is not appearing in the output. Why is this so?
You need source("C:/Mahesh/workspaces/r/temp.r", echo = TRUE)
What I would like to do is test whether a matrix is positive definite using the command chol() in R. However, if the chol() command produces an error I would like it to output false rather than producing an error and stopping the code from running. Is there an easy way to do this? I have been messing around with the command try() but it still gives me an error.
For example, if I have the matrix:
mat=matrix(c(1,2,3,1,2,3,5,5,5),nrow=3,ncol=3,byrow=F)
try(chol(mat))
this still produces an error "Error in chol.default(mat) :
the leading minor of order 3 is not positive definite."
How can I get this to produce FALSE instead of this error?
Use tryCatch, and define a handler to use in the event of an error:
tryCatch(chol(mat), error=function(e) FALSE)