sprintf
sprintf fills the blanks in a text template with your values, like a form letter where each blank is stamped with the right name. It also controls things like decimals.
In this page:
Syntax
sprintf("format %s %d %.2f", string_value, integer_value, decimal_value)
sprintf
sprintf() formats values into a string using C-style format specifiers, like %s for strings, %d for integers, and %.2f for fixed decimal places.
It gives precise control over formatting that paste() doesn't offer, such as zero-padding or fixed-width fields. This is R's equivalent of printf-style formatting found in many other languages.
Note:
sprintf("%.2f", x) is the standard way to format a number to exactly 2 decimal places for display.
Example: sprintf
name <- "Alice"
score <- 92.5
cat(sprintf("Name: %s, Score: %.1f%%\n", name, score))
cat(sprintf("Padded number: %05d\n", 42))
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Writing
%dwith a decimal number like92.5, which gives an error; use%for%.1f. - Forgetting
%%for a literal percent sign, so the format breaks. - Passing fewer values than format specifiers, which gives
too few arguments.
Chapter Summary
paste(),paste0(),nchar(),substr(), and case functions build and inspect strings.gsub(),sub(), andstrsplit()replace and split text.sprintf()formats values into strings.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: