\documentclass[12pt]{article} \usepackage{fullpage} \usepackage{noweb} \usepackage{amsmath} \title{A Literate Programming Example} \begin{document} \maketitle % Weave with % noweb::noweave("leukopt.Rnw") % write(noweb::noweb.sty, file="noweb.sty") % system("pdflatex leukopt") % Tangle with % noweb::notangle("leukopt.Rnw", target = "leukopt.R", out = "leukopt.R") \section*{The Log-Likelihood} The log-likelihood for the leukemia data is \begin{equation*} \ell(\beta_0, \beta_1, \beta_2, \delta) = -n \log\delta + \sum (z_i - e^{z_i}) \end{equation*} with $\delta = 1/\gamma$ and $z_i = (\log t_i - \beta_0 - \beta_1 x_i - \beta_2 u_i)/\delta$. The log likelihood is computed by the expression <>= -n * log(delta) + sum(z - exp(z)) @ after computing \texttt{n} and \texttt{z} as <>= n <- length(t) z <- (log(t) - beta[1] - beta[2] * x - beta[3] * u) / delta @ A function to compute the log-likelihood is therefore <>= ll <- function(beta, delta, t, x, u) { <> <> } @ \section*{The Gradient of the Log-Likelihood} The values of \texttt{exp(z)} and \texttt{exp(z) - 1} are needed several times in computing the gradient, so it is useful to compute these once and save them in variables: <>= exp_z <- exp(z) exp_z_m_1 <- exp_z - 1 @ The gradient is then computed by the expression <>= c(sum(exp_z_m_1) / delta, sum(exp_z_m_1 * x) / delta, sum(exp_z_m_1 * u) / delta, (sum(exp_z * z - z) - n) / delta) @ A function to compute the gradient of the log-likelihood is then <>= llg <- function(beta, delta, t, x, u) { <> <> <> } @ \end{document} <>= <> <> @