如何在函数内部的“ cat”内部使用“ plot”和“ abline”?

时间:2018-11-17 21:56:11

标签: r plot statistics linear-regression

我在使用以下代码时遇到问题,我不知道如何在函数中的cat指令下面介绍此指令。

df <- data.frame(x,y)
plot(y,x)
abline(lm(y ~ x))

R标记错误,指出plot(x,y)abline(lm(y~ x))之间需要逗号,但添加时显示为

Warning messages:
1: In doTryCatch(return(expr), name, parentenv, handler) :
  display list redraw incomplete
2: In doTryCatch(return(expr), name, parentenv, handler) :
  invalid graphics state
3: In doTryCatch(return(expr), name, parentenv, handler) :
  invalid graphics state

我该如何解决该问题?

请有人帮助我,谢谢。

Summary<-function(x,y,print=TRUE)
{
  p<-2
  n<-length(x)


  x<-matrix(c(rep(1,n),x),n,p)
  bg<-solve(t(x)%*%x,t(x)%*%y)
  invx<-solve(t(x)%*%x)
  xty<-t(x)%*%y
  e<-y-x%*%bg
  SCT<-sum(y^2)-n*(mean(y)^2)
  SCE<-sum(e*e)
  SCRegression<-SCT-SCE

  sigma<-SCE/(n-p)

  varbeta<-sigma*invx


  seb0 <- sqrt(varbeta[1,1])
  seb1 <- sqrt(varbeta[2,2])

  alfa <- 0.05

  valuet <- qt(1-alfa/2,n-p) 

  valuechi1 <- qchisq(1-alfa/2,n-p)
  valuechi2 <- qchisq(alfa/2,n-p)



  bg[1]-valuet*seb0
  bg[1]+valuet*seb0



  bg[2]-valuet*seb1
  bg[2]+valuet*seb1


  tvalueb1 <- bg[2]/seb1
  tvalueb1
  tvalueb0 <- bg[1]/seb0
  tvalueb0


  valuepb0 <- 2*pt(1-tvalueb0,n-p)
  valuepb0

  valuepb1 <- 2*pt(tvalueb1,n-p)
  valuepb1


  SCE/valuechi1
  SCE/valuechi2


  x0 <- mean(x) 
  yhat <- bg[1]+bg[2]*x0
  x0

  varmu <- varbeta[1,1]+x0^2*varbeta[2,2]+2*x0*varbeta[1,2]


  semu <- sqrt(varmu)
  semu

  yhat - valuet*semu
  yhat + valuet*semu

  Rsq <- SCRegression/SCT
  Rsq

  yhatt <- bg[1]+bg[2]*x
  yhatt

  ee <- y-yhatt

  df <- data.frame(x,y)

  results <- list(TSS=SCT, ESS=SCE, p=p, x=x, y=y)

  if (SCE == 0) warning("Error square sum is zero", call.=FALSE)

  if (print) {
    cat("Results for the variables", "\n\t",
        deparse(match.call()$x), " and ", deparse(match.call()$y),
        "\n\n", sep="")
    cat("The total square sum is: ", SCT, "\n\n",
        "The error square sum is: ", SCE, "\n\n",
        "The errors graph to determine homogeneity or heterogeneity is: ",plot(x,ee) , "\n\n",
        "The linear model plot: ",plot(y,x) abline(lm(y ~ x)) , "\n\n",
        sep="")
    invisible(results)
  } else {
    results
  }      
}

0 个答案:

没有答案