沒有裝過tidyverse的人請先打這行install.packages(“tidyverse”)
library
library(tidyverse)#把剛剛裝好的套件抓進來
Two way ANOVA 兩連續變項
dta <- read.table("C:/Users/Cheng_wen_sung/Desktop/09Regression/01moderation/q05.dat",header = T)#老師的檔案
summary(r2 <- lm(y~x1*x2,data = dta))
##
## Call:
## lm(formula = y ~ x1 * x2, data = dta)
##
## Residuals:
## Min 1Q Median 3Q Max
## -54.650 -11.509 2.337 9.777 46.072
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 215.38678 15.87851 13.565 <2e-16 ***
## x1 -7.38319 0.71805 -10.282 <2e-16 ***
## x2 -4.60248 0.46140 -9.975 <2e-16 ***
## x1:x2 0.20147 0.01767 11.399 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 18.39 on 96 degrees of freedom
## Multiple R-squared: 0.582, Adjusted R-squared: 0.5689
## F-statistic: 44.55 on 3 and 96 DF, p-value: < 2.2e-16
#做個ANOVA看交互作用
anova(r2)
## Analysis of Variance Table
##
## Response: y
## Df Sum Sq Mean Sq F value Pr(>F)
## x1 1 1252 1252 3.7017 0.05732 .
## x2 1 0 0 0.0004 0.98410
## x1:x2 1 43936 43936 129.9480 < 2e-16 ***
## Residuals 96 32458 338
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#這一段是用來算斜率和截距,不會就手算吧
r2coef <- coef(r2)
reg.foumula <- function(x2){
intercept <- round((r2coef[1]+r2coef[3]*x2),2)
slope <- round((r2coef[2]+r2coef[4]*x2),2)
print(c(intercept,slope))
}
#x2等於平均數時的斜率和截距
mean_line<- reg.foumula(mean(dta$x2))
## (Intercept) x1
## 46.06 0.03
#x2等於平均數+2個標準差時的斜率和截距
p_sd_line <- reg.foumula(mean(dta$x2)+2*sd(dta$x2))
## (Intercept) x1
## -51.27 4.29
#x2等於平均數-2個標準差時的斜率和截距
n_sd_line <- reg.foumula(mean(dta$x2)-2*sd(dta$x2))
## (Intercept) x1
## 143.39 -4.23
#
ggplot(data = dta,aes(x = x1,y = y))+#y丟依變項,data = 後面丟你的檔案的變數名稱,X 看你,如果控制x2時就丟x1
geom_point()+#把資料點畫在圖上
geom_abline(slope = mean_line[2],intercept = mean_line[1],col = "red")+#畫出x2等於平均數時的斜率和截距的線
geom_abline(slope = p_sd_line[2],intercept = p_sd_line[1],col = "steelblue")+#x2等於平均數+2個標準差時的斜率和截距的線
geom_abline(slope = n_sd_line[2],intercept = n_sd_line[1],col = "steelblue")+#x2等於平均數-2個標準差時的斜率和截距
theme_bw()

Two way ANOVA 兩間斷變項
#還是老師的檔案
dat = read.table('C:/Users/Cheng_wen_sung/Desktop/09Regression/02anova/q01.dat',header=TRUE)
#注意,將 A, B 定義為 factor,否則會被當成 interval scale
dat$A=factor(dat$A)
dat$B=factor(dat$B)
#2-way ANOVA
anova(r1 <- lm(X~A+B+A*B,data=dat))
## Analysis of Variance Table
##
## Response: X
## Df Sum Sq Mean Sq F value Pr(>F)
## A 1 5.281 5.281 0.9102 0.3496
## B 3 199.344 66.448 11.4524 7.428e-05 ***
## A:B 3 27.344 9.115 1.5709 0.2223
## Residuals 24 139.250 5.802
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
attach(dat)
#畫圖,x丟其中一個變項,Y丟依變項,group丟另一個獨變項
ggplot(data = dat,aes(x = A,y = X,group = B,col = B))+
geom_point()+
stat_smooth(method = "lm",se = FALSE)+
theme_bw()

一個間斷一個連續自己畫,祝大家考試順利