There is a similar question here that is asking for the width of a string in the default font size. However, I want to calculate the width of a text string in a specific font and font size.
The Base R strwidth()
function seems to be ignoring changes to the font and family parameters. Observe:
strwidth("This is cool.", units = "inches", font = 12, family = "sans")
# [1] 0.9479167
# font 10 gives same result as font 12
strwidth("This is cool.", units = "inches", font = 10, family = "sans")
# [1] 0.9479167
# monospace font gives same result as sans serif
strwidth("This is cool.", units = "inches", font = 10, family = "mono")
# [1] 0.9479167
So it appears the font and family parameters are not picked up by the function.
I have found that setting the graphics parameters with par()
makes the strwidth()
function work correctly:
par(ps = 12, family = "sans")
strwidth("This is cool.", units = "inches")
# [1] 0.8541667
par(ps = 10, family = "sans")
strwidth("This is cool.", units = "inches")
# [1] 0.7291667
par(ps = 10, family = "mono")
strwidth("This is cool.", units = "inches")
# [1] 1.083333
And these widths seem like decent estimates.
Now the issue is that par()
is creating empty PDF files in my project, because no graphics device has been passed to it. My issue is, I'm not creating any graphics. I'm just trying to find the width of a string. I shouldn't have to set the graphics parameters to do this.
So the question still remains: How do I find the width of a string of a specific font and font size in R (without creating any files)?