pres_age <- function() {
#data
all_pres <- read.csv2("http://pastebin.com/raw/B0p5fts3", stringsAsFactors=FALSE)
all_pres[, "birthdate"] <- as.Date(strptime(all_pres[,"birthdate"], "%d.%m.%Y"))
all_pres[, "inauguration.date"] <- as.Date(strptime(all_pres[,"inauguration.date"], "%d.%m.%Y"))
all_pres[, "age_at_inauguration"] <- age_at(all_pres[, "birthdate"], all_pres[, "inauguration.date"])
cand <- read.csv("http://pastebin.com/raw/q8vaN7ix", stringsAsFactors=FALSE, colClasses="character")
cand[, "birthday"] <- as.Date(strptime(cand[, "birthday"], "%m/%d/%Y"))
cand[, "inauguration.date"] <- as.Date("2017-01-20", "%Y-%m-%d")
cand[, "age_at_inauguration"] <- age_at(cand[, "birthday"], cand[, "inauguration.date"])
#base plot
plot(x=1, col="white", xlim=c(0.2, 2.8), ylim=c(35,80), ylab="Age at inauguration", xlab="", axes=FALSE)
axis(2, at=seq(40,70,by=10))
axis(1, at=c(1,2), labels=c("Democrats", "Republicans"), tick=FALSE)
#historic
max_age <- max(all_pres[, "age_at_inauguration"])
max_idx <- which(all_pres[, "age_at_inauguration"]==max_age)
abline(h=max_age, col="darkgrey", lwd=1.5)
text(x=2.8, y=max_age+1, labels=paste(all_pres[max_idx, "name"], collapse="\n"), pos=2, cex=0.6, offset=-1)
min_age <- min(all_pres[, "age_at_inauguration"])
min_idx <- which(all_pres[, "age_at_inauguration"]==min_age)
abline(h=min_age, col="darkgrey", lwd=1.5)
text(x=2.8, y=min_age+1, labels=paste(all_pres[min_idx, "name"], collapse="\n"), pos=2, cex=0.6, offset=-1)
mean_age <- mean(all_pres[, "age_at_inauguration"])
abline(h=mean_age, col="darkgrey", lty="dotted", lwd=1.5)
text(x=2.8, y=mean_age+1, labels="average", pos=2, cex=0.6, offset=-1)
# candidates
set.seed(13)
col_map <- c(Democrat="blue", Republican="red")
xpos_map <- c(Democrat=1, Republican=2)
xpos <- jitter(xpos_map[cand[, "party"]], factor=2)
points(x=xpos, y=cand[, "age_at_inauguration"], col=col_map[cand[,"party"]], pch=19)
text(x=xpos, y=cand[, "age_at_inauguration"], col=col_map[cand[,"party"]], labels=cand[,"candidate"], pos=1, cex=0.6)
}
age_at <- function(birth, at) {
if(!length(birth)==length(at)) stop("birth and at need same length")
if(!inherits(birth, "Date")) stop("birth needs to be a Date")
if(!inherits(at, "Date")) stop("at needs to be a Date")
res <- rep(NA, length(birth))
for (i in seq_along(birth)) res[i] <- length(seq(birth[i], at[i], "years"))-1
return(res)
}