-1

I have created a model in R which is essentially a matrix with different points within it assigned to different 'speciesID's and is meant to represent a colony of corals.

I am creating this function that will remove (change value to 0) points of the same species ID within a matrix. Before I run the function, I need to make sure that the point is not already 0, and is within the bounds of the matrix. I have done so using an 'if' statement.

Whenever I run the code, it is giving me the error "missing value where TRUE/FALSE needed" for my 'if' function.

I would appreciate any help someone could provide on what is wrong with my code - I have attached a sample dataset to test it on (CommunityMatrix).

set.seed(1)

SetupCommunityMatrix <- function(width,height,NumberSpecies=2)
{
CommunityMatrix <- matrix(sample(x = 0:NumberSpecies, size = 
(width*height), replace = TRUE),nrow=height,ncol=width) # So matrix with sampling between 1-no of species)
return(CommunityMatrix)
 }

CommunityMatrix <- SetupCommunityMatrix(10,10,4)

ClearClump <- function(x,y,Communitymatrix,speciesID) {
print(Communitymatrix[x,y])
print(c(x,y))

if(Communitymatrix[x,y]!=0 && y >= 1 && y <= 
ncol(Communitymatrix) && x >= 1 && x <= nrow(Communitymatrix)) { 
# so if the point is in the matrix essentially
  if(Communitymatrix[x,y] == speciesID){
    
   

  Communitymatrix[x,y] <- 0  #kill point in community
  
    Communitymatrix <- ClearClump((x- 
 1),y,Communitymatrix,speciesID)  #carry it out on the top 
    Communitymatrix <- ClearClump((x+1),y, Communitymatrix, speciesID)
    Communitymatrix <- ClearClump(x,(y-1), Communitymatrix, speciesID)
    Communitymatrix <- ClearClump(x,(y+1), Communitymatrix, speciesID)
  }

return(Communitymatrix)
}
}


test <- ClearClump(3,9,CommunityMatrix,1)
jpiversen
  • 2,584
  • 1
  • 5
  • 11
Neil
  • 1
  • 1
  • Please provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input so we can run the code to test it. – MrFlick May 27 '22 at 17:18
  • Thanks Mr Flick for your feedback - it is my first question I have asked on this platform and I hope I've made it satisfactory now! – Neil May 27 '22 at 17:22
  • @MrFlick sorry don't think I tagged you above – Neil May 27 '22 at 17:38
  • Your code runs fine for me. I cannot replicate the the error with the provided sample data. The error message you get means that the if statement evaluates to `NA`. You can get the same error with `if (NA) "will give you the same error"`. Your if statements are only dependent on `Communitymatrix`, `x`, `y` and `speciesID`. Could any of these be NA or non-numeric? – jpiversen May 27 '22 at 17:55

0 Answers0