Интерполяция строк

Простые типы / Строки

font_size <- 14
font_family <- "Arial"
style1 <- sprintf(
  "font-size: %s;font-family: \"%s\"",
  font_size, font_family)
# style1 = font-size: 14;font-family: "Arial"

# An expression goes through paste0()
style2 <- paste0("font-size: ", font_size / 2,
                 ";font-family: \"",
                 font_family, "\"")
# style2 = font-size: 7;font-family: "Arial"

# gettextf() is sprintf() for translation
style3 <- gettextf("font-size: %s", font_size)
# style3 = font-size: 14

# Without sprintf() nothing is substituted
plain <- "font-size: {font_size}"
# plain = font-size: {font_size}

cat("style1 =", style1, "\n")
cat("style2 =", style2, "\n")
cat("style3 =", style3, "\n")
cat("plain =", plain, "\n")

# %d needs a whole number
d_error <- tryCatch(sprintf("%d", font_size / 4),
                    error = conditionMessage)
cat("d_error =", d_error, "\n")
# d_error = invalid format '%d'; use format %f,
# %e, %g or %a for numeric objects