I'm using a function to calculate regressions. I need the residuals of a specific relation to relate to another variable. But I need the residuals to be calculated according to facet grid.
So, for each of the divisions the waste will be specific. This is my code, but it returns the null values.
reg = function(data) {
model1 = lm(r ~ a,data= df)
model1_sum = summary(model1)
residuals = as.data.frame(model1$residuals)
df2 = cbind(df,residuals)
names(df2)[names(df2)=="model1$residuals"] <- "residuals"
model2 = lm(residuals ~ a,data= df2)
model2_sum = summary(model2)
formula = sprintf("y= %.3f %+.3f*x",coef(model)[1], coef(model)[2])
r = model2_sum$r.squared
r2 = sprintf("r2= %.3f", r)
x = cor.test(~residuals + lat,data = df2)
r0 = sprintf("r= %.3f", sqrt(model2_sum$r.squared))
p1 = pf(model2_sum$fstatistic[1],model2_sum$fstatistic[2],model2_sum$fstatistic[3],lower.tail=F)
p =sprintf("p = %.3f", p1)
n0 = length(model2_sum$residual)
n1 = sprintf("N = %.f", n0)
data.frame(formula=formula, r=r0,r2=r2, p=p,n=n1, stringsAsFactors=FALSE)
}
df2_math = ddply(data, c("continente","banco"), df2)
df2_math