Reputation: 31
Hello Stackoverflow Users,
I am having trouble running an lm function in R on every row in my matrices, and I would really love if I didn't have to run it manually 1000 times. So basically I have 2 matrices with rows (1:1000) and cols (1:100), and I would like to run an lm function for each row in x for the representative row in y.
My code is:
sigmaianden=1
Beta=1
set.seed(seed=20)
xi=rnorm(100)
capn=100
capm=1000
xi.1=matrix(c(rep(c(xi),each=capm)),nrow=capm,ncol=capn)
epsiloni.1=NULL
for (i in 1:100000) {
epsiloni.1[i]=rnorm(1,0,sigmaianden*xi.1[i]^2)
}
epsiloni.11=matrix(epsiloni.1,nrow=1000,ncol=100)
yi.1=Beta*xi.1+epsiloni.11
Personally I was thinking something like:
for (i in 1:1000){
model[i]=lm(yi.1[i,1:100]~xi.1[i,1:100])
}
But that doesn't even give me a result. I will be grateful for any help.
Upvotes: 2
Views: 285
Reputation: 48241
You are close. lm
returns a list
, so that what you want to do is to put your models to another list:
models <- vector("list", 1000)
for (i in 1:1000)
models[[i]] <- lm(yi.1[i,1:100] ~ xi.1[i,1:100])
Then you may iterate again and extract resid(models[[i]])
or coef(models[[i]])
or anything else. However, now models
is quite convenient to use, so that instead of for
loops you can use just e.g.
R <- sapply(models, resid)
dim(R)
[1] 100 1000
or
C <- sapply(models, coef)
dim(C)
[1] 2 1000
Upvotes: 1