The base R function by
is what you want.
# make up some sample data
dataSet <- data.frame(Y = iris$Sepal.Length,
X1 = iris$Sepal.Width,
X2 = iris$Petal.Length,
V = iris$Species)
# apply the `lm` function by the value of `V`
by(data = dataSet[c("Y","X1","X2")],
INDICES = dataSet$V,
FUN = lm,
formula = Y ~ .)
In the by
function, data
is the data you want to apply the function to. INDICES
is a vector of factors or list of factors with one value corresponding to each row of data
indicating how you want the data split up. FUN
is the function you want applied to the subsets of your data. In this case, lm()
needs the extra parameter formula
indicating how you want to model your data, so you can easily pass that as and extra formula
parameter in the by
function.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…