3

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?

3
  • Please first provide a Minimal Complete and Verifiable Example. Without that, it's quite hard to figure out the problem. I do see a typo though in the return statement (g instead of p), but this shouldn't be the main issue, I figure. Commented Jul 1, 2017 at 9:21
  • do you want the values to be on the plot? Commented Jul 1, 2017 at 9:31
  • It would be much better, but my question was about that print the values in the console Commented Jul 1, 2017 at 9:33

1 Answer 1

3

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

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

8 Comments

I tried and it returns this [[1]] Call: lm(formula = df[, 2] ~ df[, 1]) Coefficients: (Intercept) df[, 1] 3.898e-16 -7.059e-01 [[2]] Error in .Call.graphics(C_palette2, .Call(C_palette2, NULL)) : invalid graphics state
I did not draw the plot
To get plot, you need to type out$p at the command prompt. The function only returns the plot.
I've tested the code I've given. It works. So, it seems something else is the matter.
No it did not unfortunately. it pasted it NULL for out$p
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.