[R] Comparing two regression slopes
Spencer Graves
spencer.graves at pdf.com
Wed Jul 30 19:22:28 CEST 2003
I'm afraid of your manual ANOVA. It may be correct, but it won't easily
generalize. Instead, how about the following:
> df1 <- data.frame(x=1:3, y=1:3+rnorm(3))
> df2 <- data.frame(x=1:3, y=1:3+rnorm(3))
>
> fit1 <- lm(y~x, df1)
> s1 <- summary(fit1)$coefficients
> fit2 <- lm(y~x, df2)
> s2 <- summary(fit2)$coefficients
>
> db <- (s2[2,1]-s1[2,1])
> sd <- sqrt(s2[2,2]^2+s1[2,2]^2)
> df <- (fit1$df.residual+fit2$df.residual)
> td <- db/sd
> 2*pt(-abs(td), df)
[1] 0.9510506
The function "attributes" helped me figure this out.
hope this helps. spencer graves
Martin Biuw wrote:
> Hello,
> I've written a simple (although probably overly roundabout) function to
> test whether two regression slope coefficients from two linear models on
> independent data sets are significantly different. I'm a bit concerned,
> because when I test it on simulated data with different sample sizes and
> variances, the function seems to be extremely sensitive both of these. I
> am wondering if I've missed something in my function? I'd be very
> grateful for any tips.
>
>
> Thanks!
>
> Martin
>
>
> TwoSlope <-function(lm1, lm2) {
>
> ## lm1 and lm2 are two linear models on independent data sets
>
> coef1 <-summary(lm1)$coef
> coef2 <-summary(lm2)$coef
>
> sigma <-(sum(lm1$residuals^2)+sum(lm2$residuals^2))/(lm1$df.residual +
> lm2$df.residual-4)
> SSall <-sum(lm1$model[,2]^2) + sum(lm2$model[,2]^2)
> SSprod <-sum(lm1$model[,2]^2) * sum(lm2$model[,2]^2)
>
> F.val <-(as.numeric(coefficients(lm1)[2]) - as.numeric(coefficients(lm2)
> [2]))^2/((SSall/SSprod)*sigma)
>
> p.val <-1-pf(F.val, 1, (lm1$df.residual + lm2$df.residual-4))
>
> cat("\n\nTest for equality between two regression slopes\n\n")
> cat("\nCoefficients model 1:\n\n")
> print(coef1)
>
> cat("\nCoefficients model 2:\n\n")
> print(coef2)
>
> cat("\nF-value on 1 and", lm1$df.residual + lm2$df.residual-4, "degrees
> of freedom:" ,F.val, "\n")
> cat("p =", ifelse(p.val>=0.0001, p.val, "< 0.0001"), "\n")
>
> }
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
More information about the R-help
mailing list