Linear Regression and group by in R

Since 2009, dplyr has been released which actually provides a very nice way to do this kind of grouping, closely resembling what SAS does. library(dplyr) d <- data.frame(state=rep(c(‘NY’, ‘CA’), c(10, 10)), year=rep(1:10, 2), response=c(rnorm(10), rnorm(10))) fitted_models = d %>% group_by(state) %>% do(model = lm(response ~ year, data = .)) # Source: local data frame [2 … Read more

Add regression line equation and R^2 on graph

Here is one solution # GET EQUATION AND R-SQUARED AS STRING # SOURCE: https://groups.google.com/forum/#!topic/ggplot2/1TgH-kG5XMA lm_eqn <- function(df){ m <- lm(y ~ x, df); eq <- substitute(italic(y) == a + b %.% italic(x)*”,”~~italic(r)^2~”=”~r2, list(a = format(unname(coef(m)[1]), digits = 2), b = format(unname(coef(m)[2]), digits = 2), r2 = format(summary(m)$r.squared, digits = 3))) as.character(as.expression(eq)); } p1 <- p … Read more