#' @title mlokCorMat
#' @description Create correlation matrix with use of ggplot and reshape2 packages.
#'
#' This is a funciton that helps to easily generate correlation matrices that can
#' be used in reports. The input data must have at least two numeric variables, and
#' will automatically exclude any fields that cannot be conformed into numeric data type.
#'
#' @param x dataframe with at least two numeric fields.
#' @return The red cells indicate negative correlation between variables; green indicates positive correlation.
#'
#' @examples
#' Name <- c('Otis', 'Michael', 'Sharon', 'Robin' )
#' Height <- c(207, 178, 164, 180)
#' Weight <- c(250, 156, 132, 149)
#' Profile <- data.frame(Name, Height, Weight)
#'
#' mlokCorMat(Profile)
#'
#' @export
#' @import data.table
#' @import reshape2
#' @import tidyverse
#' @import logging
mlokCorMat<-function(x)
{
#only look into the numeric variables of the data frame
x <- dplyr::select_if(x, is.numeric)
#only looks at bottom half of the correlation matrix
logging::loginfo('remove upper triangle from matrix...')
get_lower_tri<-function(cormat){
cormat[upper.tri(cormat)] <- NA
return(cormat)
}
##ggheatmap creation
logging::loginfo('melting matrix for ggplot...')
cormat <- round(cor(x),3)
cormat <- get_lower_tri(cormat)
melted_cormat <- reshape2::melt(cormat)
logging::loginfo('constructing confusion matrix...')
ggheatmap <- ggplot2::ggplot(data=melted_cormat, aes(x=Var1,y=Var2,fill=value))+
geom_tile(color='white')+
scale_fill_gradient2(low='dark red',mid='grey',high='dark green',
midpoint=0, limit=c(-1,1),
name='')+
labs(title='Correlation Matrix',x='Variable 1',y='Variable 2')+
theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1),
legend.position = 'bottom')
return(ggheatmap)
logging::loginfo('confusion matrix successfully created.')
}
#' @title mlokNumericize
#' @description Accelerating the Data Cleansing Process
#'
#' removes special characters from a string or a vector of strings
#' and converts string into a numeric data type.
#'
#' @param x the string or list of strings that needs to be converted into numeric data type
#' @return x will be returned in numeric data type, removing special characters.
#' @examples
#' # String:
#' string <- " `~1#$%^&4*()_+"
#' mlokNormalize(string)
#'
#' # Vector:
#' vector <- c('$14.00', '5,000,000', '25%', '>$10,000')
#' mlokNormalize(vector)
#'
#' @export
mlokNumericize <- function(x) {
# remove all alphabetical characters in each string.
x <- gsub("[a-zA-z]", "", x)
# removes all special characters
x <- as.numeric(gsub("[\\$^?,() #_@!&*+=`~>%<]", "", x))
return(x)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.