Reputation: 3941
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.
Upvotes: 3
Views: 12394
Reputation: 18487
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
Upvotes: 4
Reputation: 43265
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
Upvotes: 5