我想编写一个带有原始数据回归图形输出的函数和一个用于修改数据的函数。原始数据回归应该是一种选择。此外,图表中应该有图例。这是我的问题:如果我选择选项:orig.plot=FALSE,一切正常。但是当我选择另一个选项时:orig.plot=TRUE,我的图例的位置不是很令人满意。
# Generation of the data set
set.seed(444)
nr.outlier<- 10
x<-seq(0,60,length=150);
y<-rnorm(150,0,10);
yy<-x+y;
d<-cbind(x,yy)
# Manipulation of data:
ss1<-sample(1:nr.outlier,1) # sample size 1
sri1<-sample(c(1:round(0.2*length(x))),ss1) # sample row index 1
sb1<-c(yy[quantile(yy,0.95)<yy])# sample base 1
d[sri1,2]<-sample(sb1,ss1,replace=T) # manipulation of part 1
ss2<-nr.outlier-ss1 # sample size 2
sri2<-sample(c(round(0.8*length(x)+1):length(x)),ss2) # sample row index 2
sb2<-c(yy[quantile(yy,0.05)>yy])# sample base 2
d[sri2,2]<-sample(sb2,ss2,replace=T) # manipulation of par 2
tlm2<-function(x,y,alpha=0.95,orig.plot=FALSE,orig.ret=FALSE){
m1<-lm(y~x)
res<-abs(m1$res)
topres<-sort(res,decreasing=TRUE)[1:round((1-alpha)*length(x))] # top alpha*n residuals
topind<-rownames(as.data.frame(topres)) # indices of the top residuals
x2<-x[-as.numeric(topind)] #
y2<-y[-as.numeric(topind)] # removal of the identified observations
m2<-lm(y2~x2)
r2_m1<-summary(m1)$'r.squared'
r2_m2<-summary(m2)$'r.squared'
if(orig.plot==TRUE){
par(mfrow=c(2,1))
plot(x,y,xlim=range(x),ylim=c(min(d[,2])-30,max(d[,2]+30)),main="Model based on original data")
abline(m1$coef);legend("topleft",legend=bquote(italic(R)^2==.(r2_m1)),bty="n")
}
plot(x2,y2,xlim=range(x),ylim=c(min(d[,2])-30,max(d[,2]+30)),main="Model based on trimmed data")
abline(m2$coef);
legend("topleft",legend=bquote(atop(italic(R)^2==.(r2_m2),alpha==.(alpha))),bty="n")
return(if(orig.ret==TRUE){list(m1=m1,m2=m2)} else{m2})
}
tlm2(d[,1],d[,2])
tlm2(d[,1],d[,2],orig.plot=T)
谁能给我一个提示?
先感谢您!