3

I would like to write a function that creates a plot of a set of numbers and adds a regression line. As of now, I can still create the plot but I either get an error with the plot, or some sort of Null response.

My function without a regression line that returns no null looks like this:

fun<-function(){
+   x<-c(1,2,3,4,5)
+   y<-c(1,2,3,4,5)
+   LR<-lm(x~y)
+   
+   return(plot(x,y))
+ }
> fun()

Nice and Pretty with just a plot as a result

if I add the regression line to the plot, I still get the plot but I also get a null response

> fun<-function(){
+   x<-c(1,2,3,4,5)
+   y<-c(1,2,3,4,5)
+   LR<-lm(x~y)
+   p<-plot(x,y)
+   a<-abline(LR)
+   return(p)
+ }
> fun()
NULL

or an error

> fun<-function(){
+   x<-c(1,2,3,4,5)
+   y<-c(1,2,3,4,5)
+   
+   LR<-lm(x~y)
+   
+   p<-plot(x,y)
+   a<-abline(LR)
+   
+   return(p,a)
+ }
> fun()
Error in return(p, a) : multi-argument returns are not permitted

or two nulls

> fun<-function(){
+   x<-c(1,2,3,4,5)
+   y<-c(1,2,3,4,5)
+   
+   LR<-lm(x~y)
+   
+   p<-plot(x,y)
+   a<-abline(LR)
+   
+   return(list(p,a))
+ }
> fun()
[[1]]
NULL

[[2]]
NULL

Sorry if this seems ridiculously nit picky, but in the actual data set it can get ugly.

2 Answers 2

5

Does this do what you want?

fun <- function(x, y) {
  plot(x, y)
  abline(lm(x~y))
}

fun(1:10, 10:1)

If you're hoping for a plot object to return for further manipulation, you can use ggplot:

fun <- function(df) {
  ggplot(df, aes(X, y)) + geom_point()
}

df <- data.frame(x=1:10, y=10:1)
p <- fun(df)

# examine p
str(p)

# plot p
p
Sign up to request clarification or add additional context in comments.

2 Comments

+1 for ggplot (I wouldn't recommend str(p) on a complex graphic though ;) ; lattice graphics can also be stored this way.
@baptiste That's a good point! str(p) will be a big nasty yuk that only Hadley can comprehend. The str(p) was more to make the point that we got something back vs. calling str on the return value of the OP's function.
4

Do you really need the function to return the plot object? Or is it sufficient to plot it directly?

I'm addicted to ggplot2 for that kind of stuff. This function does both (printing the plot and returning it as an object)

fun <- function(dataset){
  require(ggplot2)
  p <- ggplot(dataset, aes(x = x, y = y)) + geom_smooth(method = "lm") + geom_point()
  print(p)
  return(p)
}

p1 <- fun(data.frame(x = c(1,2,3,4,5), y = rnorm(5)))
p1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.