R- multiple returns in function to create a plot

r

Solution

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

Problem

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.

Original source