Fills a character string up to a size and handles multibyte encodings (differently from sprintf).

string_fill(
  x = "",
  n = NULL,
  symbol = " ",
  right = FALSE,
  center = FALSE,
  na = "NA"
)

Arguments

x

A character vector.

n

Integer scalar, possibly equal to NULL (default). The size up to which the character vector will be filled. If NULL (default), it is set to the largest width in the character vector x. To handle how the character is filled, see the arguments symbol, right and center.

symbol

Character scalar of length 1, default is a space (" "). It is the symbol with which the string will be filled.

right

Logical scalar, default is FALSE. If TRUE, then the filling of the string is done from the left, leading to right-alignment.

center

Logical scalar, default is FALSE. If TRUE, then the filling of the string will be balanced so as to center the strings.

na

Character scalar or NA. Default is "NA" (a character string!). What happens to NAs: by default they are replaced by the character string "NA".

Value

This functions returns a character vector of the same lenght as the vector in input.

Details

If you use character filling of the form sprintf("% 20s", x) with x``containing multibyte characters, you may be suprised that all character strings do not end up at the same lenght (the occurrence of this problem depends on many things: encodings are a mess). string_fill` uses only base R functions to compensate this. It is slightly slower but, in general, safer.

It also looks a bit like base::format(), but slightly different (and a bit faster, but more restrictive).

See also

String operations: string_is(), string_get(), string_clean(), string_split2df(). Chain basic operations with string_ops(). Clean character vectors efficiently with string_clean().

Use string_vec() to create simple string vectors.

String interpolation combined with operation chaining: string_magic(). You can change string_magic default values with string_magic_alias() and add custom operations with string_magic_register_fun().

Display messages while benefiting from string_magic interpolation with cat_magic() and message_magic().

Other tools with aliases: cat_magic_alias(), string_magic(), string_magic_alias(), string_ops_alias(), string_vec_alias()

Author

Laurent R. Berge

Examples


x = c("apple", "pineapple") 

# simple fill with blank
cat(paste0(string_fill(x), ":", c(3, 7), "€"), sep = "\n")
#> apple    :3€
#> pineapple:7€

# center fill
cat(paste0(string_fill(x, center = TRUE), ":", c(3, 7), "€"), sep = "\n")
#>   apple  :3€
#> pineapple:7€

# changing the length of the fill and the symbol used for filling
cat(paste0(string_fill(x), ":", 
           string_fill(c(3, 7), 3, "0", right = TRUE), "€"), sep = "\n")
#> apple    :003€
#> pineapple:007€

# na behavior: default/NA/other
x = c("hello", NA) 
string_fill(x)
#> [1] "hello" "NA   "
string_fill(x, na = NA)
#> [1] "hello" NA     
string_fill(x, na = "(missing)")
#> [1] "hello    " "(missing)"