user1912925
user1912925

Reputation: 781

Linear regression based upon categorical variables in r

I have had a look over the various r resources but cannot find an obvious solution to my problem. If this is answered elsewhere a pointer in the right direction would be useful. With the following dataset:

    tmp <- c(35,35,35,35,35,36,36,36,36,36)
    experiment <- factor(tmp)
    rpm <- c(10,20,40,80,120,10,20,40,80,120)
    x <- c(678,1889,3416,8916,17917,665,1385,3377,8551,16793)
    test <- data.frame(experiment,rpm,x)

I would like to perform regression, for instance a linear regression using lm on rpm against x:

    lm(x ~ rpm)

Thus in this example I would have two regressions, one for experiment 35 and one for experiment 36. I could subset the data but my actual data will have upwards of 200 experiments and I am wondering if I can do this with just a few lines of code?

Upvotes: 1

Views: 509

Answers (1)

krlmlr
krlmlr

Reputation: 25444

There's plyr:

library(plyr)
dlply(test, .(experiment), function(df) with(df, lm(x ~ rpm)))

Upvotes: 1

Related Questions