0
votes

I keep getting this error message when I run my code, and I'm not sure what I need to do to fix it.

My code is as follows:

gwmh<-function(target,N,x,sigmasq){  
  p<-add.var()
  samples<-c(x,p)
  for(i in 2:N){
    prop<-rnorm(1,0,sqrt(sigmasq))
    if(runif(1)<min(1,(target(x+abs(prop)*p))/target(x))){
      x<-x+prop
    samples<-rbind(samples,c(x,p))} else{
      p<--p
    samples<-rbind(samples,c(x,p))
    }
  }
  samples[(1:N)]  ##delete after testing
} 

The error says: Error in if (runif(1) < min(1, (target(x + abs(prop) * p))/target(x))) { : missing value where TRUE/FALSE needed

(add.var is a function i created to generate p in {-1,1} randomly)

2
This means that the if(test_expression) tests an expressions that is neither TRUE or FALSE but missing. Have you checked that the data input into the function has no missing values? - Fnguyen
And target is another one of your functions that you haven't provided? It's impossible to help unless you provide a lot more information. Obviously line 5 is the problem child. - Edward
@miasarah the error msg is saying that: the runif(1)<min(1,(target(x+abs(prop)*p))/target(x)) this particular code is not evaluating to True or False. Ideally if conditions must have expression that evaluates to either T or F. Just debug the code written as condition. use browser() method before if condition to debug. - nikn8

2 Answers

1
votes

I tested my comment and feel more comfortable offering it as an answer.

Try the following

if(TRUE){print("Test")}
# prints "Test"

if(FALSE){print("Test")}
# prints nothing

if(NA){print("Test")}
# throws your error

So within this expression:

runif(1)<min(1,(target(x+abs(prop)*p))/target(x))

the result is neither TRUE or FALSE but NAand seeing as runif()should not throw any missings it has to be in the rhs of the comparison.

Assuming that target, x, and sigmasq are all values from a df and not functions there is probably a missing value there. If this is the case and also intended you have to add an exception for catching and handling these missings that might look like this:

# test being your test expression
if(
  if(is.na(test) {Do Stuff for missing values}
  else {original IF statement}
0
votes

You need to add na.rm=TRUE to the min function to account for possible NA in x.

Your function will fail if x contains NA.

target <- function(x) dnorm(x, 0, 1) 
add.var <- function() runif(1, -1, 1)

gwmh <- function(target,N,x,sigmasq){  
  p <- add.var()
  samples<-c(x,p)
  for(i in 2:N){
    prop<-rnorm(1,0,sqrt(sigmasq))
    if(runif(1) < min(1, (target(x+abs(prop)*p))/target(x), na.rm=TRUE)){  # <- Here
      x<-x+prop
      samples<-rbind(samples,c(x,p))} else{
        p<--p
        samples<-rbind(samples,c(x,p))
      }
  }
  samples[(1:N)]  ##delete after testing
} 

Now try:

gwmh(target, N=2, x=c(1,2,NA,3), sigmasq=2)
# [1] 1.00 3.14