如何绘制每组的回归(多图)

时间:2019-05-26 19:28:16

标签: r dplyr regression plyr lm

我有一个每年的邻里和犯罪率的时间序列数据(以下示例)。

neighbourhood  year  rate
      1        2009  43.5   
      1        2010  34.7
      1        2011  40.8
      2        2009  28.9
      2        2010  33.8
      2        2011  24.4

我按组(每个邻域)应用样条回归,并使用plyr包提取每个样条的系数。我想为每个街区绘制样条回归图。我使用d_ply进行了绘制,并且工作正常,但是无法为这些图绘制样条曲线

# for one neighbourhood I used this:

library(plyr)
library(splines)
model1 <- lm(formula=data$rate ~ bs(data$year, 5))
plot(data$quarter, data$rate, pch=19)
lines(data$quarter, fitted(model1))
# Now for group by neighbourhoods I used plyr function :

model2 <- dlply(data, "Neighborhood", function(rep) 
  lm(formula=data$rate ~ bs(data$year, 5)))

ldply(model2, coef) 

# And plot per neighbourhood by d_ply:

d_ply(data, "Neighborhood", transform, 
      plot(year, rate, main=unique(Neighborhood), pch=19)) 
lines(data$year, fitted(model2))

它工作正常,并显示了每个邻域的散点图,但我无法在这些图上画线。

0 个答案:

没有答案