[R] How to calculate the number of times a given string can be displayed in the width of a grid viewport

Sébastien Bihorel pomchip at free.fr
Wed Aug 3 17:51:03 CEST 2011


There was too many spelling mistakes in my original post so I have
decided to re-submit it. So here is it

Dear R users,

I am trying to determine how many characters can be displayed within
the width of an open grid viewport. Unfortunately, the arithmetic
operation that seems obvious in this case is not permitted with unit
objects (see example below). Although there is a brute force way to
get this number (using a while loop where the string would be modified
by appending the original string to itseft until its width is larger
than the width of the viewport), this solution seems a bit overworked.
Any suggestion would be welcome.

Sebastien

require(grid)
dev.off()
dev.new()
nstr <- ''
str <- 'OXXXX'

nInWidth <- floor(unit(1,'npc')/unit(1,'strwidth',str))  # Does not work

nInWidth <- 0

convertWidth(unit(1,'strwidth',nstr),'npc')

while
(unclass(convertWidth(unit(1,'strwidth',paste(nstr,str,sep='')),'npc'))[1]
- 1 <=.Machine$double.eps){
  nInWidth <- nInWidth +1
  nstr <- paste(nstr,str,sep='')
}

nInWidth

grid.text(paste(rep(str,nInWidth),collapse=''),
          x = unit(0.5, "npc"), y = unit(0.5, "npc"),
          draw = TRUE)



More information about the R-help mailing list