Skip to content

Instantly share code, notes, and snippets.

@RHDZMOTA
Created April 29, 2016 19:08
Show Gist options
  • Save RHDZMOTA/61a7a95f42345333f47f21db0f50564b to your computer and use it in GitHub Desktop.
Save RHDZMOTA/61a7a95f42345333f47f21db0f50564b to your computer and use it in GitHub Desktop.
Save file as "generate_dataset.R" to use with "inverse_function.R". This specific script was used in wordpress post in [add link]
# Example of inverse function
# Generating x-axis, pdf and cdf numeric values.
# last modifyed: 29/04/2016
library(ggplot2)
library(tibble)
library(tidyr)
# Mathematical function ---------------------------------------------------
pdf_example <- function(x){
flag <- F
if(x >= -4 & x <= -1) flag <- T
if(x >= 1 & x <= 4) flag <- T
if(flag)
-5 * (x^2 - 1) * (x^2 - 16) / 1044
else
0
}
# Create x-axis, pdf and cdf values --------------------------------------
n <- 5000
dataset <- data_frame( x = seq(-5, 5, 10/n ))
dataset$pdf <- sapply(X = unlist(dataset$x), FUN = pdf_example)
aux <- 0
freq_acum <- numeric()
for(i in 1:(n+1)){
freq_acum[i] <- dataset$pdf[i] + aux
aux <- dataset$pdf[i] + aux
}
dataset$cdf <- freq_acum / sum(dataset$pdf)
dataset <- gather(dataset, dens, freq, -x)
# Plot the results --------------------------------------------------------
g <- ggplot(dataset, aes(x, freq, group = dens)) + theme_minimal() +
geom_ribbon(aes(ymin = 0, ymax = freq, fill = dens), alpha =0.6, color = "black") +
xlab("value") + ylab("frequency") + scale_fill_brewer() +
ggtitle("Dataset generated - {x-axis, pdf, cdf}")
# g + geom_segment(aes(x = 0, xend = 0, y = 0, yend = 1/2), color = "dark blue", size = 0.75) +
# geom_segment(aes(x = -5, xend = 0, y = 1/2, yend = 1/2), color = "dark blue", size = 0.75)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment