Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

r - Generate an array of regression models without for loop

I have a data set with columns Y, X1, X2 and V. While Y, X1 and X2 are continuous, V is a categorical variable. Assuming V has 10 categories, I want to create 10 linear regression models and store the results (coefficients, p-values, R-Sq, etc) in another table. Is there a way to do it with data.table without using for loops? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...