0

Very weird behavior using levelplot inside a function:

> foo <- function() { require(lattice); levelplot(matrix(rnorm(100),10,10)) }
> bar <- function() { require(lattice); levelplot(matrix(rnorm(100),10,10)); return(1) }
> foo()  ## graph gets generated
Loading required package: lattice
> graphics.off()
> bar()  ## NO GRAPH GETS GENERATED
[1] 1

foo() works as expected, and bar() does not generate any plot. Any ideas?

user2623214
  • 133
  • 4
  • It is a duplicate, although a subtle one. `foo` actually returns the result of `levelplot`, which is then implicitly printed when run at the console. – joran Dec 03 '13 at 18:08

1 Answers1

1

By default, the function returns the last generated object. In function foo, this is the plot. In function bar, it's 1.

If you want to generate a plot and return another object, you have to create the plot with print.

bar <- function() { 
         require(lattice); 
         print(levelplot(matrix(rnorm(100),10,10))); 
         return(1) }

When you call bar(), the plot will be created and 1 will be returned.

Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168