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"
# 表达式要通过 paste0() 拼入
style2 <- paste0("font-size: ", font_size / 2,
";font-family: \"",
font_family, "\"")
# style2 = font-size: 7;font-family: "Arial"
# gettextf() 是会翻译格式字符串的 sprintf()
style3 <- gettextf("font-size: %s", font_size)
# style3 = font-size: 14
# 不用 sprintf() 就不会发生替换
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 需要整数
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