Sébastien Bihorel
2011-Aug-03 14:51 UTC
[R] How to calculate the number of time a given string can be displayed in the width of a grid viewport
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 be permitted with unit objects (see example below). Although it isa brut 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 bigger 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) [[alternative HTML version deleted]]