Slim Shady
Slim Shady

Reputation: 220

function that takes a response variable and a predictor variable and produces a scatterplot with a simple regression line


myModel = function(resp, pred){
  linMod = lm(resp~pred)
  myPlot = plot(pred,resp, main="predictor~response")
  abline(linMod, col="red")
  return(myPlot)
}

What I want to create is an R function that takes a response variable and a predictor variable as input and produces a scatterplot with a fitted simple linear regression line.

I then type in > myModel(c(0.25,0.5,1.0),c(1,2,3)) into the console and then it produces a scatter plot but then I get NULL in my console. Why do I get it? Also, is my function correct?

Upvotes: 0

Views: 200

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 270170

plot does not return a value, just NULL, so if the intention was to return the plot then replace the return line in the body of the function with recordPlot() like this:

myModel = function(resp, pred){
  linMod = lm(resp~pred)
  plot(pred,resp, main="predictor~response")
  abline(linMod, col="red")
  recordPlot()
}

Then we can do this:

p <- myModel(c(0.25,0.5,1.0),c(1,2,3))  # perform plotting
dev.off()  # destroy window with plot
print(p)  # restore plot

Upvotes: 2

koenniem
koenniem

Reputation: 576

Because plot cannot be saved to variables; It can only be plotted directly. Your solution is simple:

myModel = function(resp, pred){
  linMod = lm(resp~pred)
  plot(pred,resp, main="predictor~response")
  abline(linMod, col="red")
}

Upvotes: 2

Related Questions