Created
October 23, 2012 18:11
-
-
Save cdesante/3940431 to your computer and use it in GitHub Desktop.
color1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
####################################################### | |
# Example 4: Casting/Melting with custom functions # | |
####################################################### | |
#Let's first define a function, SE, to represent the standard error of a | |
#variable: | |
library(gridExtra) | |
library(ggplot2) | |
SE <- function(X) { | |
(sd(X, na.rm=TRUE)/ sqrt(length(X)-1) ) | |
} | |
ANES <- read.csv("http://www.oberlin.edu/faculty/cdesante/assets/downloads/ANES.csv") | |
head(ANES) | |
ANES$caseid <- 1:dim(ANES)[1] | |
TRUST <-melt(ANES, id=c("year", "dems"), na.rm=TRUE) | |
head(TRUST) | |
TRUST <- TRUST[TRUST$variable=="trust",] | |
#first thing I'll cast are the means of the "trust" variable over | |
#time, based on the respodnent's two-party identification | |
MEANS <- cast(TRUST, year+dems~variable, mean, na.rm=TRUE) | |
head(MEANS) | |
SEs <- cast(TRUST, year+dems~variable, SE) | |
head(SEs) | |
TRUST.plot <- cbind(MEANS$year,MEANS$dems,SEs$dems, MEANS$trust, SEs$trust, | |
(MEANS$trust - 1.96* SEs$trust), (MEANS$trust + 1.96* SEs$trust) ) | |
TRUST.plot | |
TRUST.plot <- TRUST.plot[complete.cases(TRUST.plot),] | |
colnames(TRUST.plot) <- c("year", "dems", "dems.2", "means", | |
"SE", "lows", "highs") | |
DF <- as.data.frame(TRUST.plot) | |
T1 <- ggplot(data = DF) + geom_pointrange(aes(x = year, y = means, | |
ymin = lows, ymax = highs, colour=factor(dems)) ) | |
T1 <- T1 + labs(title="geom_pointrange, T1") | |
T1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment