calling levelplot from a function

236 Views Asked by At

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?

1

There are 1 best solutions below

0
On

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.