crayon is a package for adding color to printed output, e.g.
library(crayon)
message(red('blue'), green('green'), blue('red'))
However, nchar used on its output is wrong:
# should be 4 characters
nchar(red('1234'))
# [1] 14
I tried all the different type= options for nchar, to no avail -- how can I get R to tell me the correct number of characters in this string (4)?

First, note that the output of
redis just a plain string:The garbled-looking parts (
\033[31mand\033[39m) are what are known as ANSI escape codes -- you can think of it here as signalling "start red" and "stop red". While the program that converts the character object into printed characters in your terminal is aware of and translates these,ncharis not.ncharin fact sees 14 characters:To get the 4 we're after,
crayonprovides a helper function:col_ncharwhich first appliesstrip_styleto get rid of the ANSI markup, then runs plainnchar:So you can either do
nchar(strip_style(x))yourself if you find that more readable, or usecol_nchar.