Creating models for each group in dataframe column in R

173 Views Asked by At

I would like to create a naiveBayes model per group of values of column TN. Here is the code:

library(party)
airq <- subset(airquality, !is.na(Ozone))
ct <- ctree(Ozone ~ ., data = airq,  controls = ctree_control(maxsurrogate = 3))
airq$TN<-factor (ct@where)

Here is an example:

> tail (airq)
    Ozone Solar.R Wind Temp Month Day TN
1     7      49 10.3   69     9  24   2
2    14      20 16.6   63     9  25   5
3    30     193  6.9   70     9  26   3
4    14     191 14.3   75     9  28   2
5    18     131  8.0   76     9  29   5
6    20     223 11.5   68     9  30   3

I want to build a NaiveBayes model per value:

model[i] <- naiveBayes(Ozone ~ ., data = dat[i])

dat[1] will contain lines 1 and 4 (TN=2) for creating first model,dat[2] contains lines 2 and 5 for (TN=5) for the second model, dat[3] contains lines 3 and for third model (TN=3). So finally, I'll be able to sum it up: for each unique group values in TN I'll have its model. Like this:

    TN_val  model     Based on Source_Lines
1     2     model[1]   1,4
2     5     model[2]   2,5
3     3     model[3]   3,6
0

There are 0 best solutions below