https://github.com/cran/live
Raw File
Tip revision: 84995cbbede9c862a146af6456642e9bc0174904 authored by Mateusz Staniak on 05 May 2018, 14:47:30 UTC
version 1.5.3
Tip revision: 84995cb
helpers.R
#' Alert user if NAs are present
#'
#' @param data Data frame from which observations are generated by sample_locally.
#' @param explained_instance A row in an original data frame (as a data.frame).
#'
#' @return Warning message
#'

check_for_na <- function(data, explained_instance) {
  if(any(is.na(explained_instance))) warning("Missing values present in explained instance.")
  if(any(is.na(data))) warning("Missing values present in dataset. NAs will be omitted while sampling.")
}


#' Check if data, explained instance and size make sense.
#' 
#' @param data Data frame from which observations will be sampled.
#' @param explained_instance Instance around which points will be sampled.
#' @param size Number of observation in simulated dataset
#' 
#' @return Produces an error if any of conditions aren't met.
#' 

check_conditions <- function(data, explained_instance, size) {
  if(nrow(data) == 0) stop("Empty data frame")
  if(ncol(data) == 0) stop("Data frame has no columns")
  if(size <= 0) stop("Size has to be a positive integer")
  if(any(colnames(data) != colnames(explained_instance))) 
    stop("Explained instance must have the same variables as data")
}


#' Set date values to one value 
#' 
#' @param data Data frame to change.
#' @param explained_instance Instance that will be explained.
#' @param col_names Names of columns to be fixed
#' 

set_constant_variables <- function(data, explained_instance, col_names) {
  cols <- (1:ncol(data))[which(colnames(data) %in% col_names)]
  if(length(cols) == 0) {
    return(data)
  } else {
    for(k in cols) {
      data.table::set(data, j = as.integer(k), 
                      value = explained_instance[1, as.integer(k)])
    }
    data
  }
}


#' Create regression or classification task.
#'
#' @param model Name of a used model in mlr format.
#' @param dataset Data frame on which model will be trained.
#' @param target_var Name of column in dataset containing explained variable.
#' @param weights Weights for observations.
#'
#' @return mlr task object
#'

create_task2 <- function(model, dataset, target_var, weights = NULL) {
  if(grepl("regr", model)) {
    mlr::makeRegrTask(id = "lime_task",
                      data = as.data.frame(dataset),
                      target = target_var,
                      weights = weights)
  } else {
    mlr::makeClassifTask(id = "lime_task",
                         data = as.data.frame(dataset),
                         target = target_var)
  }
}
back to top