0

I have written a function to build a plot using grid grobs, and a method to get the width of the resulting gTree. The method function is recognised when run from a script but not when I try to load as part of a package. In my package code file I have:

require(grid)
require(reshape)

widthDetails.bHMLegend <- function(x){
  minX0 <- min(do.call(unit.c, lapply(x$children, grobX, theta = 180)))
  maxX1 <- max(do.call(unit.c, lapply(x$children, grobX, theta = 0)))
  return(grobWidth(segmentsGrob(x0 = minX0, x1 = maxX1)))}

bHMLegend <- function(sizeBreaks, title){
    gTree(name="BHMLegend", cl="bHMLegend", children = gList(
      rectGrob(x = 0.5, y = c(0.5:(length(sizeBreaks)-0.5))*unit(0.5, "cm"), 
      height = unit(0.5, "cm"), width = unit(0.5, "cm"), just=c("left", "centre")),
      textGrob(sizeBreaks, x = unit(0.5, "npc") + unit(0.5, "cm") + unit(1, "char"), 
      y = seq(0.5, length(sizeBreaks)-0.5, 1)*unit(0.5, "cm"), just=c("left", "centre")),
      textGrob(title, x = unit(0.5, "npc") + unit(0.25, "cm"), 
      y = unit(0.5, "cm")*(length(sizeBreaks)+0.5), just=c("centre", "bottom"))))
}

In my testing script file I have:

require(devtools)
load_all()
tree <- bHMLegend(c(0, 10, 20, 30, 40, 50, 60, 70, 80), title="Legend Title")

convertUnit(grobWidth(tree), "cm")

widthDetails.bHMLegend <- function(x){
  minX0 <- min(do.call(unit.c, lapply(x$children, grobX, theta = 180)))
  maxX1 <- max(do.call(unit.c, lapply(x$children, grobX, theta = 0)))
  return(grobWidth(segmentsGrob(x0 = minX0, x1 = maxX1)))}

convertUnit(grobWidth(tree), "cm")

The first convertUnit() call returns 0cm, but the second time after loading the function directly into the global environment I get the expected answer (~2.42cm). How do I get this to work from the package?

Thanks (edited to include full example code)

  • If you build and install the package, and then load it in the normal way, does it work? If not, please post complete code to illustrate the problem. – user2554330 Nov 18 '21 at 17:27
  • I got 0cm like you until I exported the S3 method, then I got an error `Error in grid.Call(C_convert, x, as.integer(whatfrom), as.integer(whatto), : VECTOR_ELT() can only be applied to a 'list', not a 'NULL'` – user2554330 Nov 18 '21 at 19:43
  • Thank you, this helped! This is my first package and I hadn't tried experimenting with NAMESPACE yet. I didn't get the same error as you after exporting the method (just 0cm again) but I got it to work after exporting the method and importing the gTree function! – GreenPepperAvalanche Nov 20 '21 at 08:53

0 Answers0