Reputation: 2722
Let say I have a list of three data frames
set.seed(55)
df1 <- data.frame(a=rnorm(6), b=rnorm(6), c=rnorm(6))
df2 <- data.frame(a=rnorm(6), b=rnorm(6), c=rnorm(6))
df3 <- data.frame(a=rnorm(6), b=rnorm(6), c=rnorm(6))
l <- list(df1, df2, df3)
I now like to do a linear model with a and c of every data frame. I tried the following
for(i in l) {
x <- (lm(l[[i]]$a~l[[i]]$c))
}
However I get the following error
Error in l[[i]] : invalid subscript type 'list'
I'd like to have a list with every element an lm of a and c. Any help would be appreciated. Thank you very much!
Upvotes: 0
Views: 1936
Reputation: 263481
The accepted answer is to be preferred but it might be useful for people coming from a for-loop mentality to be told that the lapply
solution ( at least the one where it's result is assigned to 'x') is equivalent to this:
x<-list();
for(i in seq_along(l) ) {
x[[i]] <- lm(a~c, data=l[[i]])
}
Upvotes: 0
Reputation: 520
If you want to stay with the format you proposed (the for loop) you need to use something like 1:length(l)
in your for loop statement.
Also, if you keep assigning things to x you will keep overwriting it. In what I have below I am assigning the linear model to the 24th, 25th, and 26th letters of the alphabet, so you have a lm called x, y, and z. Other suggested solutions are much cleaner.
for(i in 1:length(l)) {
assign(letters[24:26][i], (lm(l[[i]]$a~l[[i]]$c)))
}
Upvotes: 0
Reputation: 193687
You can do this with a simple lapply
, like this:
lapply(l, lm, formula = a ~ c)
Upvotes: 6