Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return plot and values from a function together [duplicate]

I have a function like this:

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

l<-lm(y~x)
return (list(l, g))
    }

and I want to return both plot and the values, but it doesn't return the plot and I face this error:

Error in .Call.graphics(C_palette2, .Call(C_palette2, NULL)) :
invalid graphics state

What can I do?

like image 927
minoo Avatar asked Nov 19 '25 01:11

minoo


1 Answers

The following works, and you can get the plot. However, R warns that's not the way to do it.

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

  l <- lm(y~x, data=dataset)
  return (list(l, p))
}

dataset <- data.frame(x= 1:10, y=1:10)
out <- fun(dataset)

Edit: I've had a look about the warning, it seems like something you can ignore. See link https://stat.ethz.ch/pipermail/r-devel/2016-December/073554.html

like image 187
Suren Avatar answered Nov 20 '25 19:11

Suren