we have a hypothesis relating the density of a US state with the life expectancy in that state. let’s write some code to explore this.
to allow evaluating R code, evaluate this source block by putting point inside and typing [C-c C-c] (control C followed by control C) and giving permission for it to be evaluated.
(org-babel-do-load-languages
'org-babel-load-languages
'((emacs-lisp . t) (R . t)))
(normally, you would do this by customizing
org-babel-load-languages
.)
then, to allow editing R code, evaluate this source block, etc.
(require 'ess-r-mode)
(this is required because i’m running emacs -Q
, so i don’t have my
normal customizations.)
let’s evaluate this
state.abb[match("Wyoming", state.name)]
but, we might need to do that many times. let’s write a subroutine to do that, passing the table from which the return value should be taken as a second argument.
lookup <- function(state, where) {
where[match(state, where)] # XXX
}
lookup("Wyoming", state.abb)
we seem a bit low on results. what’s wrong?
state.x77[,"HS Grad"][match("Wyoming", state.name)]
but, maybe we could re-use the lookup function? using :noweb
?
add a name to the source block that held the lookup function.
lookup <- function(state, where) {
where[match(state, state.name)]
}
okay, now we can include it with :noweb
<<lookup>>
lookup("Wyoming", state.x77[,"HS Grad"])
for our project, we’re going to be accessing various state statistics, so we realize we’d like also to have the lookup of state statistics as a common routine.
we’ll need some utilty code to return columns of state.x77
(which we
can include with :noweb
).
state_stat <- function(which) {
state.x77[,which]
}
and, make use of that, see if it works.
<<state_stat>>
<<lookup>>
lookup("Wyoming", state_stat("HS Grad"))
we take the calculations of the relevant statistics out of the block
that actually does the graphing. to pass the results, we can’t use
:noweb
. we can, however, use :var
, which allows the results of
one source block to be used as input to another source block.
a simple routine to produce the life expectancies of states. note
that :results
is set to table
. (adding drawer
means we can hide
it away easier, to keep the visual buffer less cluttered.)
<<state_stat>>
state_stat("Life Exp")
now, what is the density? population=/=area
, i guess.
<<state_stat>>
state_stat("Population") %/% state_stat("Area") # XXX
and, now, write the graph routine. reminder: we aren’t accessing
density
and expectancy
via :noweb
, but, rather, via :var
(but,
we still use :noweb
).
i hope it works!
<<lookup>> # note: syntax checker doesn't understand =:noweb= references
plot(density, expectancy,
panel.first = lines(stats::lowess(density, expectancy), lty = "dashed"),
pch = ".", cex = 1.2, col = "blue")
text(density, expectancy, lookup(rownames(state.x77), state.abb),
pos=1, cex=1, col="red")
(open the resulting file with [C-c C-o].)