formatC()
The function formatC() provides an alternative way to format numbers based on C style syntax.
Rather than a scientific argument, formatC() has a format argument that takes a code representing the required format. The most useful are:
"f"for fixed,"e"for scientific, and"g"for fixed unless scientific saves space
When using scientific format, the digits argument behaves like it does in format(); it specifies the number of significant digits. However, unlike format(), when using fixed format, digits is the number of digits after the decimal point. This is more predictable than format(), because the number of places after the decimal is fixed regardless of the values being formatted.
formatC() also formats numbers individually, which means you always get the same output regardless of other numbers in the vector.
The flag argument allows you to provide some modifiers that, for example, force the display of the sign (flag = "+"), left align numbers (flag = "-") and pad numbers with leading zeros (flag = "0"). You'll see an example in this exercise.
Este exercício faz parte do curso
String Manipulation with stringr in R
Instruções do exercício
The vectors income, percent_change, and p_values are available in your workspace.
- First, compare the behavior of
formatC()toformat()by callingformatC()onxwithformat = "f"anddigits = 1. This is the same vector you used withformat(), do you see the difference? - Call
formatC()onywithformat = "f"anddigits = 1. Notice howdigitshas consistent behavior regardless of the vector you format. - Format
percent_changeto one decimal place after the decimal point. - Format
percent_changeto one decimal place after the decimal point and addflag = "+". This forces the display of the sign. - Format
p_valuesusingformat = "g"anddigits = 2. This can be useful, since if there are any p-values in scientific notation, they must be < 0.0001.
Exercício interativo prático
Experimente este exercício completando este código de exemplo.
# From the format() exercise
x <- c(0.0011, 0.011, 1)
y <- c(1.0011, 2.011, 1)
# formatC() on x with format = "f", digits = 1
___
# formatC() on y with format = "f", digits = 1
___
# Format percent_change to one place after the decimal point
___
# percent_change with flag = "+"
___
# Format p_values using format = "g" and digits = 2
___