R/ResIndex.R

Defines functions ResIndex

Documented in ResIndex

ResIndex <- function(df,class,f=0.7,N=5,seed=NULL){
  if(!is.null(seed)){
    set.seed(seed)
  }
  classname <- deparse(substitute(class))
  ## determine the size of sample
  len <- nrow(df)
  nsize <- f*len

  ## Calculate the max possible transitions in dataframe
  l <- levels(df[,c(classname)])
  p = 0
  for (i in l) {
    q = nrow(df[df[,c(classname)] == i,])/nrow(df)
    if (q <= 0.5){
      p = p + 2*q
    }
  }
  max = min(1.0, p)

  ## Find the number of transitions in a dataframe
  transitions <- function(dframe){
    trows <- nrow(dframe)
    total <- 0
    for (i in 1:trows-1){
      check = identical(dframe[,c(classname)][i],dframe[,c(classname)][i+1])
      if (!check)
      {
        total <- total + 1
      }
    }
    return (total/trows)
  }

  df_random <- df[sample(1:nrow(df)),]
  ref_resol <- max - transitions(df_random)

  ## transitions after sorting on a variable
  grouping <- function(dframe,a){
    result <- transitions(dframe[order(dframe[,c(a)], decreasing=FALSE),])
    return (result)
  }

  x <- colnames(df)
  df_imp = data.frame(matrix(nrow=0, ncol=length(x)-1))

  ## Max possible transitions and transition after randomizing the rows
  message("Maximum Transitions: ",round(max,4))
  message("Random  Transitions: ",round(ref_resol,4))

  for (i in 1:N) {
    sample <- df[sample(1:nrow(df),nsize),]
    vec <- list()
    for (i in x) {
      y <- identical(i,classname)
      if (!y){
        resolution <- (max - grouping(sample, i))/ref_resol
        vec <- c(vec, round(resolution,4))
      }
    }
    df_imp <- rbind(df_imp,vec)
  }
  colnames(df_imp) <- x[x!=classname]
  imp <- data.frame(colMeans(df_imp))
  colnames(imp) <- c("Resolution Index")
  imp
}

Try the ResIndex package in your browser

Any scripts or data that you put into this service are public.

ResIndex documentation built on April 4, 2025, 2:33 a.m.