I think I am having an issue regarding variable scope but can't figure out how to work around it. Essentially I create a data frame in an R function and then use ggplot to call variables out of that data frame. I keep getting an error stating that the object dataframe was not found.
library("ggplot2")
library("reshape2")
library("RColorBrewer")
singleColor <- brewer.pal(8, "Dark2")[1]
cbPalette <- c("#999999", "#E69F00", "#56B4E9", "#009E73",
"#F0E442", "#0072B2", "#D55E00", "#CC79A7")
set.seed(42) ## for the differents sample call
posRespt <- data.frame(Section = rep(1, 11),
Order = 1:11,
Question = LETTERS[1:11],
Response = rep('Very Important', 11),
Males = sample(1:40, 11, replace = TRUE),
Females = sample(1:40, 11, replace = TRUE))
posRespt$Total <- with(posRespt, Males + Females)
BannerDemoPlots <- function(titleText, fname, yLabel, xLabel, DemColumns){
temp <- subset(posRespt, select=c(1:3, DemColumns))
tempDemoDF <- melt(temp, id=c("Section","Order", "Question"))
tempDemoDF <- tempDemoDF[order(tempDemoDF$Order, tempDemoDF$variable),]
# print(tempDemoDF)
DemoPlots <- ggplot(data=tempDemoDF, aes(Question, value, group=variable, fill=cbPalette)) + geom_bar(stat="identity", aes(fill=variable), position="dodge") + coord_flip() + ylim(0, 100)
DemoTheme <- labs(title= titleText, x=xLabel, y=yLabel)
AxisColors <- theme(axis.text.x = element_text(colour = "black"), axis.text.y = element_text(colour = "black"))
BarValues <- geom_text(aes(data=tempDemoDF, y=variable, label = value), position = position_dodge(width=1))
Colors <- scale_fill_manual(values=cbPalette)
DemoPlot <- DemoPlots + DemoTheme + AxisColors + Colors + BarValues
DemoPlot
ggsave(filename=fname, plot=(DemoPlot), width=6.5, height=8.5, units='in', dpi=300)
return(tempDemoDF)
}
BannerDemoPlots(titleText="Gender", xLabel='', yLabel="Percent Responding 'Very Important'", fname="/home/huntdj/Army STARRS/Programs/Banner Data Charts/EnlistmentGender.eps", DemColumns=c(6:7))
The ERROR I get states:
Error in eval(expr, envir, enclos) : object 'tempDemoDF' not found
Any help would be greatly appreciated!