Just for posterity, I thought I would post the result of everyone's
help and my efforts to create this (probably only useful to me)
function. Hopefully the thought process is useful to someone in the
future:
## Function ####
grouped_cor_ <- function(data, x, y, form){
x <- lazyeval::as.lazy(x)
y <- lazyeval::as.lazy(y); fac <-
as.name(as.character(form)[2])
cor1 <- lazyeval::interp(~ cor.test(x, y,method="spearman",na.action
= "na.exclude")$estimate, x = x, y = y)
corp <- lazyeval::interp(~ cor.test(x, y,method="spearman",
na.action = "na.exclude")$p.value, x = x, y = y)
mnx <- lazyeval::interp(~ mean(x, na.rm=TRUE), x = x, y = y)
mny <- lazyeval::interp(~ mean(y, na.rm=TRUE), x = x, y = y)
summarise_( group_by_(data, fac), rho=cor1, pval=corp, xcoord=mnx, ycoord=mny)
}
corHighlight <- function(Data, x, y, form){
cordf<-grouped_cor_(Data, x = substitute(x), y = substitute(y),
form=substitute(form))
cordf$prho <- paste("rho=",round(cordf$rho,3), "\n
p-value=",round(cordf$pval,3), sep=" ")
plt<-ggplot(Data, aes_q(x = substitute(x), y = substitute(y))) +
geom_text(data=cordf, aes_q(x=substitute(xcoord),
y=substitute(ycoord),
label=substitute(prho)), colour='red') +
geom_point(size=2, alpha=0.3) +
facet_wrap(form)
print(plt)
}
##################################
Generalized to work any dataset (I hope):
corHighlight(Data=iris,
x=Petal.Width,
y=Petal.Length, form = ~Species)
corHighlight(Data=mtcars,
x=mpg,
y=hp, form = ~cyl)
Thank you for everyone's help.
Sam