# Iterative Mean of Means Infinite Loop for calculating H-t Index

I'm trying to create a function that will calculate an Ht-Index for Quantifying the Fractal or Scaling Structure of Geographic Features (but am new to R)

which basically just finds nested means of continuous data (raster in this case) and separates them into 2 groups: heads and tails (values above and below the means). The Ht-Index is the number of times (-1) the 'heads' group can be subdivided without being greater than some threshold (e.g., 45%) of the distribution of both groups. I'm not sure how to efficiently do this in R but here is my failed attempt which creates an infinite loop iterating over the same input.

``````require(raster)

foo <- raster('/foobar.img')

hindex <- function(x){
iCounter <-0
repeat{
head <- x[x>mean(x)]  # need to replace x each iteration for head and tail
tail <- x[x<mean(x)]
if (headpct >.45) break # If head is > 45% of values stop
else
if (length(head)== 1) break # if head is only one value stop
iCounter <- iCounter+1
}
return(iCounter-1)
}
``````

Without looking too deeply into what you are doing, returning the number of iterations is fairly straight forward. I have now made it so that infinite loops don't happen and made the threshold one of the function parameters.

``````hindex <- function(x, threshold){
iCounter <- 0 # Make counter 0
repeat{