상호작용이 있는 다중회귀분석에서 moderator에 따른 output을 시각화하려고 합니다.
fit=lm(mpg~wt*hp,data=mtcars)
calEquation=function(fit,moderator){
intercept=moderator*fit$coef[2]+fit$coef[1]
slope=moderator*fit$coef[4]+fit$coef[3]
label=paste0("wt=",moderator)
df=data.frame(intercept,slope,label)
df
}
df=calEquation(fit,moderator=2:4)
df
## intercept slope label
## 1 33.37517 -0.064405794 wt=2
## 2 25.15855 -0.036557646 wt=3
## 3 16.94193 -0.008709498 wt=4
또한 다음과 같은 ggplot이 있습니다.
library(ggplot2)
theme_set(theme_bw())
p=ggplot(data=mtcars)+geom_point(aes(x=hp,y=mpg))
p
ggplot의 좌표 정보를 얻어올 수 있는 함수는 다음과 같이 만들수 있습니다.
#'Get aspect information og a ggplot
#'@param p A ggplot object
#'@importFrom ggplot2 layer_scales
#'@export
getAspectRatio=function(p){
xmin=layer_scales(p)$x$range$range[1]
xmax=layer_scales(p)$x$range$range[2]
ymin=layer_scales(p)$y$range$range[1]
ymax=layer_scales(p)$y$range$range[2]
ratio=(xmax-xmin)/(ymax-ymin)
list(xmin=xmin,xmax=xmax,ymin=ymin,ymax=ymax,ratio=ratio)
}
이때 이 ggplot과 데이터를 인수로 받아들여 ggplot을 반환하는 함수 add_lines를 작성해보셔요.
출력은 다음과 같습니다.
add_lines(fit,p,moderator=2:4)
add_lines(fit,p,moderator=1:5,lty=1:5,color=1:5,size=1)