Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
library(package = "ggplot2")
library(package = "reshape2")
f_normalizar <- function( p_data )
{
x_min <- min(x = p_data)
x_max <- max(x = p_data)
( p_data - x_min ) / ( x_max - x_min )
}
f_computos <- function( p_data )
{
media <- mean( x = p_data, na.rm = T )
mediana <- median( x = p_data, na.rm = T )
moda <- unique( p_data )
moda <- moda[ which.max( x = tabulate( bin = match( x = p_data, table = moda ) ) ) ]
data.frame( Media = media
, Mediana = mediana
, Moda = moda
)
}
f_transformar <- function( p_data, p_summ )
{
# Melt Data
mltd_data <- melt( data = p_data
, variable.name = "Atributo"
, value.name = "Value"
)
# Melt Summary
mltd_summ <- melt( data = p_summ
, id.vars = "Atributo"
, variable.name = "Metrica"
, value.name = "Value"
)
list( mltd_data = mltd_data
, mltd_summ = mltd_summ
)
}
f_generarGrafica <- function( p_mltd )
{
( ggplot()
+ geom_histogram( data = p_mltd$mltd_data
, aes( x = Value
, fill = Atributo
)
, bins = 40
, color = "black"
, alpha = 0.5
)
+ geom_vline( data = p_mltd$mltd_summ
, aes( xintercept = Value
, color = Metrica
, linetype = Metrica
)
, size = 1
)
+ facet_wrap( facets = ~Atributo
, scales = "fixed"
)
+ labs( x = "Value"
, y = "Frequency"
)
+ scale_color_manual( values = c("goldenrod","deeppink3","dodgerblue") )
+ scale_fill_brewer( palette = "Greens", guide = F )
+ theme_bw()
+ theme( panel.grid = element_blank()
, strip.background = element_rect( fill = "dodgerblue4" )
, strip.text = element_text( color = 'white' )
, axis.text = element_text( size = 10.5 )
, plot.title = element_text( size = 11 )
, legend.title = element_text( size = 11 )
)
)
}
f_crearHistograma <- function( p_data, p_columnas )
{
# Iterar sobre columnas y normalizar
my_data <- mapply( FUN = f_normalizar
, USE.NAMES = T
, SIMPLIFY = T
, p_data[ , p_columnas ]
)
my_data <- as.data.frame.matrix( x = my_data )
# Crear resumen de numeros
my_summ <- lapply( FUN = f_computos
, X = my_data
)
my_summ <- do.call( what = rbind, args = my_summ )
my_summ$Atributo <- row.names( x = my_summ )
row.names( x = my_summ ) <- NULL
# Transformar Datasets
mltd <- f_transformar(p_data = my_data, p_summ = my_summ)
# Crear grafica
grafica <- f_generarGrafica( p_mltd = mltd )
list( grafica = grafica
, datos = my_data
, resumen = my_summ
)
}
histograma <- f_crearHistograma(iris, 1:4)
histograma$grafica
histograma$resumen
histograma$datos
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment