library(dplyr)
library(ggplot2)
dat <- datasets::anscombe
datLong <- data.frame(
group = rep(1:4, each = 11),
x = unlist(dat[,c(1:4)]),
y = unlist(dat[,c(5:8)])
)
rownames(datLong) <- NULL
datLong
## group x y
## 1 1 10 8.04
## 2 1 8 6.95
## 3 1 13 7.58
## 4 1 9 8.81
## 5 1 11 8.33
## 6 1 14 9.96
## 7 1 6 7.24
## 8 1 4 4.26
## 9 1 12 10.84
## 10 1 7 4.82
## 11 1 5 5.68
## 12 2 10 9.14
## 13 2 8 8.14
## 14 2 13 8.74
## 15 2 9 8.77
## 16 2 11 9.26
## 17 2 14 8.10
## 18 2 6 6.13
## 19 2 4 3.10
## 20 2 12 9.13
## 21 2 7 7.26
## 22 2 5 4.74
## 23 3 10 7.46
## 24 3 8 6.77
## 25 3 13 12.74
## 26 3 9 7.11
## 27 3 11 7.81
## 28 3 14 8.84
## 29 3 6 6.08
## 30 3 4 5.39
## 31 3 12 8.15
## 32 3 7 6.42
## 33 3 5 5.73
## 34 4 8 6.58
## 35 4 8 5.76
## 36 4 8 7.71
## 37 4 8 8.84
## 38 4 8 8.47
## 39 4 8 7.04
## 40 4 8 5.25
## 41 4 19 12.50
## 42 4 8 5.56
## 43 4 8 7.91
## 44 4 8 6.89
datLong %.%
group_by(group) %.%
do(function(DF) {
resLm <- lm(y ~ x, data = DF)
coef(summary(resLm))
})
## [[1]]
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 3.0001 1.1247 2.667 0.02573
## x 0.5001 0.1179 4.241 0.00217
##
## [[2]]
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 3.001 1.125 2.667 0.025759
## x 0.500 0.118 4.239 0.002179
##
## [[3]]
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 3.0025 1.1245 2.670 0.025619
## x 0.4997 0.1179 4.239 0.002176
##
## [[4]]
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 3.0017 1.1239 2.671 0.025590
## x 0.4999 0.1178 4.243 0.002165
ggplot(data = datLong,
mapping = aes(x = x, y = y, group = group)) +
layer(geom = "point") +
layer(geom = "smooth", method = "lm", fullrange = TRUE) +
facet_wrap( ~ group) +
theme_bw() +
theme(legend.key = element_blank())