Using format() with numbers
The behavior of format()
can be pretty confusing, so you'll spend most of this exercise exploring how it works.
Recall from the video, the scientific
argument to format()
controls whether the numbers are displayed in fixed (scientific = FALSE
) or scientific (scientific = TRUE
) format.
When the representation is scientific, the digits
argument is the number of digits before the exponent.
When the representation is fixed, digits
controls the significant digits used for the smallest (in magnitude) number. Each other number will be formatted to match the number of decimal places in the smallest number. This means the number of decimal places you get in your output depends on all the values you are formatting!
For example, if the smallest number is 0.0011, and digits = 1
, then 0.0011 requires 3 places after the decimal to represent it to 1 significant digit, 0.001. Every other number will be formatted to 3 places after the decimal point.
So, how many decimal places will you get if 1.0011 is the smallest number? You'll find out in this exercise.
This is a part of the course
“String Manipulation with stringr in R”
Exercise instructions
- Format
c(0.0011, 0.011, 1)
withdigits = 1
. This is like the example described above. - Now, format
c(1.0011, 2.011, 1)
withdigits = 1
. Try to predict what you might get before you try it. - Format
percent_change
by choosing thedigits
argument so that the values are presented with one place after the decimal point. - Format
income
by choosing thedigits
argument so that the values are presented as whole numbers (i.e. no places after the decimal point). - Format
p_values
using a fixed representation.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Some vectors of numbers
percent_change <- c(4, -1.91, 3.00, -5.002)
income <- c(72.19, 1030.18, 10291.93, 1189192.18)
p_values <- c(0.12, 0.98, 0.0000191, 0.00000000002)
# Format c(0.0011, 0.011, 1) with digits = 1
___
# Format c(1.0011, 2.011, 1) with digits = 1
___
# Format percent_change to one place after the decimal point
___
# Format income to whole numbers
___
# Format p_values in fixed format
___