1

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)]  
    headpct <- length(head)/sum(length(head),length(tail)) 
    if (headpct >.45) break # If head is > 45% of values stop
        else
            if (length(head)== 1) break # if head is only one value stop
    x <- head
    iCounter <- iCounter+1
    }
return(iCounter-1) 
}
2

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{
    head <- x[x>mean(x)]
    tail <- x[x<mean(x)]
    headpct <- length(head)/sum(length(head),length(tail))
    if (headpct > threshold) break # If head is > threshold of values stop
        else
            if (length(head)== 1) break # if head is only one value stop
    x <- head # reset X
    iCounter <- iCounter + 1 # Only increment if break doesn't occur
    }
return(iCounter) 
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.