“non-numeric argument to binary operator” error in R

I’ve been trying to run this function and the “non-numeric argument to binary operator” pops up. I’ve seen quite a few questions similar to mine, yet I still can’t figure out what is the issue with my code.

TakeOneIndStep <- function(Itl, N){     # Itl is a vector  
  foo <- ListMaintenance(Itl, N)        # is a vector of same length as Itl. Displays the coordinates of coalesced walks. 
  incrm <- sample(c(-1, 0, 1), size = length(Itl), replace =  T, prob = c(0.25, 0.5, 0.25))
  for (j in 1:length(Itl)){
    if(Itl[j] %in% foo){
     Itl[j] <- (Itl[j] + incrm[j]) %% N
   }else{
     Itl[j] <- "H"              # H is a "placeholder", just to indicate that that particular chain has coalesced and no longer is updated. 
   }
 }
  return(Itl)
}

The error happens on the sixth line Itl[j] <- (Itl[j] + incrm[j]) %% N.

The code for the auxiliary functions:

ListMaintenance <- function(Temp, N){    # Temp is a vector
  rez <- CheckCoalescence(Temp)
  fubar <- vector()
  for(i in 1:length(rez)){
    for(x in 0:(N-1)){if (x %in% rez[[i]]){fubar[x] <- min(rez[[i]])}
    }
  } 
  return(fubar)                  # output is a vector. Coordinates with the same value have the index of the smallest occurrence.  
}

CheckCoalescence <- function(Pts){
  mar <- unname(split(seq_along(Pts), Pts))
  return(mar)
}

On the big picture, I’m trying to simulate a random walk process with more than two different starting points. So the argument Itl would be the values of each walk at time (t-1), and this function will recursively update these values.

For practical purpose, I tried to test the function with A <- c(0, 2, 3, 2, 6) and TakeOneIndStep(A, N = 9)

In this case, A is just an arbitrary vector. There’s more code to simulate the walk, but I just presented the part that is causing the error.

Leave a Comment