问题
Given:
Consider the density function $\phi$ defined on $\mathbb{R}$ for $a\in \mathbb{R}$ and $b \in \mathbb{R}_+^\star$ such that $\forall x \in \mathbb{R}$, $$ \phi(x; a,b) = \frac{1}{\sqrt{2\pi b^2}}e^{-\frac{1}{2}\left(\frac{x-a}{b}\right)^2}. $$ Consider now the so-called Bart Simpson probability density function $f$ given by \begin{eqnarray} \label{eq:bart:1d:1} f(x) = \frac{1}{2}\phi(x; 0,1) + \frac{1}{10}\sum_{j=0}^4{\phi(x; (j/2)-1, 1/10)}. \end{eqnarray}
Questions:
- Plot the pdf $f$ in $[-\pi, \pi]$.
Attempt:
So, I understand the notation $\phi(x; a,b)$ -- $a$ is the mean and $b$ is the standard deviation for the density function $\phi$.
I can write R
code to simulate $\phi$ and $f(x)$:
calc_cdf <- function(a, b, x) {
coef <- 1/sqrt(2*pi*b^2)
expon <- exp(-0.5*((x-a)/b)^2)
return(coef * expon)
}
calc_pdf <- function(x) {
term1 <- 0.5 * calc_cdf(0, 1, x)
sum2 <- 0
for (j in 0:4) { sum2 = sum2 + calc_cdf(j/2 - 1, 0.1, x) }
term2 <- 0.1 * sum2
return(term1 + term2)
}
Now this is where I'm stuck: How on earth do I plot a PDF? There are libraries for plotting defined PDFs, such as EnvStats::pdfPlot, but that doesn't allow you to define your own PDF and plot it.
So far as I can tell, there are no libraries for doing so. I can't find any reference to a "Bart Simpson" PDF either.
Please, any help would be greatly appreciated!
回答1:
You don't need a whole library to plot a function. It's built into base R.
See ?plot.function
and ?curve
, including their examples.
e.g.
plot(dnorm,-3,3)
plot(function (x) dgamma(x,shape=2),0,6)
来源:https://stackoverflow.com/questions/55172882/plotting-custom-pdf-in-r