如何创建一个在R中创建回归模型的循环?

如何创建一个在R中创建回归模型的循环?,r,for-loop,lm,R,For Loop,Lm,我有这样的数据,有很多物种多年的时间序列数据 Species year x species1 2000 56 species1 2001 12 species1 2002 40 species2 2000 30 species2 2001 40 species2 2002 50 对于每个物种,我想创建一个x与年份的回归模型,我还想绘制每个模型并找到每个趋势线的斜率。要做到这一点,我想我应该使用某种类型的循环。假设您只使用lm,诀窍是将数据参数改为不同

我有这样的数据,有很多物种多年的时间序列数据

Species    year  x
species1   2000  56
species1   2001  12
species1   2002  40
species2   2000  30
species2   2001  40
species2   2002  50

对于每个物种,我想创建一个x与年份的回归模型,我还想绘制每个模型并找到每个趋势线的斜率。要做到这一点,我想我应该使用某种类型的循环。

假设您只使用lm,诀窍是将数据参数改为不同的子集

speciesList <- unique(df$Species)

for(i in 1:length(speciesList){

    lmmodel <- lm(x ~ year, data = subset(df, Species == speciesList[i]))

    #Now do all the stuff you want with lmmodel, e.g. plot, find slope, etc
}
我不打算为您编写一整段函数代码,但这是最棘手的一点。有很多关于如何从模型中绘制数据的资源,包括趋势线等

使用子集函数,我们可以一次提取一个物种的数据子集。我用unique得到了物种列表,然后一个元素一个元素地浏览


我也不确定x或year是否是你的自变量,所以我做了一个合乎逻辑的假设,那就是year

这是一个没有循环的解决方案

# some artificial data
set.seed(1)
daf <- data.frame(species = factor(paste0("species", c(rep(1:3, 10)))), 
                  year = rep(2000:2009, 3), x = sample(1:100, 30))

library(dplyr)
library(broom)

lm_fit <- daf %>% group_by(species) %>% 
  do(fit = lm(x ~ year, .))

tidy(lm_fit, fit) # or as.data.frame(tidy(lm_fit, fit)) to get a data.frame

# # A tibble: 6 x 6
# # Groups:   species [3]
# species  term          estimate std.error statistic p.value
# <fct>    <chr>            <dbl>     <dbl>     <dbl>   <dbl>
# 1 species1 (Intercept)   2508       7132       0.352   0.734 
# 2 species1 year        -    1.23       3.56   -0.346   0.738 
# 3 species2 (Intercept) -11250       4128      -2.73    0.0260
# 4 species2 year             5.64       2.06    2.74    0.0256
# 5 species3 (Intercept)    461       7460       0.0618  0.952 
# 6 species3 year        -    0.206      3.72   -0.0554  0.957 

library(ggplot2)
ggplot(daf, aes(x = year, y = x)) + geom_smooth(method = "lm", se = FALSE) +
  facet_wrap(~species)

这个问题你问得太多了。如果你不能1为数据的子集做一个循环2绘制一个模型3找到趋势线的斜率,那么它们是三个不同的东西,我敢说你至少可以很容易地找到堆栈溢出上的点2和点3。