Hi James,
Here is a suggestion:

# Data
set.seed(123)
Factor <- rep(1:4, each = 20)
X <- rnorm(80, 25, 4)
Y <- 5 + 1.5*Factor*X + rnorm(80)
df <- data.frame(X, Y, Factor)

# Splitting df
sdf <- with(df, split(df, Factor))

# betas and R2
do.call(rbind, lapply(sdf, function(miniDF){
                                         fit <- lm(Y ~ X, data = miniDF)
                                        out <- c(coef(fit), R2 =
summary(fit)$r.squared)
                                        out
                                            }
                            )
           )

HTH,
Jorge


On Wed, Sep 30, 2009 at 11:10 PM, jimdare <> wrote:

>
> Hi,
>
> I'm sure these are basic problems so I apologise in advance for my
> ignorance.  I have a dataset with X, Y, and a Factor with 4 levels.  I am
> trying to figure out how to use lm() to find the r2 value, slope and
> intercept of an X~Y regression, for each level of the Factor.  Is there a
> way to do this automatically without having to specify different subsets of
> the factor?
>
> my code so far:
>
> Regression<-lm(Y~X, data=dataset, subset=factor(Factor))
>
> Also, when I plot this dataset using:
>
> xyplot(Y~X|factor(Factor), data=dataset, aspect="iso",
> type=c("p","g","r"),pch=21,cex=1)
>
> I get a four panel plot (one for each level of the factor) with a
> regression
> line for each.  How do I figure out the r2 value and coefficients of each
> regression line and add them as text to the plot.
>
> Thanks for your help!
>
> James
>
>
>
> --
> View this message in context:
> http://www.nabble.com/Regression-for-levels-of-a-factor-xyplot-type%3D%22r%22-tp25692526p25692526.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help@r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

	[[alternative HTML version deleted]]


