How to space-pad unicode string character in R?

Viewed 121

I am trying to pad a character with a space using sprintf() (but any base R alternative is would be fine).

It works as expected for letter "a" but for "β" it won't work:

sprintf('% 2s', 'a')
#> [1] " a"
sprintf('% 2s', 'β')
#> [1] "β"
sprintf('% 3s', 'β')
#> [1] " β"

I guess it has to do with the fact that it takes two bytes (i.e., two sprintf's "characters") to represent the "β" string... but so, I could I change my code to make it work and pad with spaces in a way that "β" is understood as one character (i.e., one-visible character).

1 Answers

Convert the string to native first. This worked for me on Windows but not on https://rdrr.io/snippets/ which reports its .Platform$os.type as unix.

s <- 'β'; n <- 3 # inputs

sprintf("%*s", n, enc2native(s))  # or hard code the 3 and drop n
## [1] "  ß"

Alternately use paste0 or substring<- with strrep or convert the string to X's, perform the sprintf and then convert back. These worked on Windows and on https://rdrr.io/snippets/ .

# 2
paste0(strrep(' ', n - nchar(s)), s)
## [1] "  β"

# 3
`substring<-`(strrep(" ", n), n - nchar(s) + 1, n, s)
## [1] "  ß"

# 4
sub("X+", s, sprintf("%*s", n, strrep("X", nchar(s))))
## [1] "  β"
Related