开始使用免费开始使用

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.

本练习是课程的一部分

String Manipulation with stringr in R

查看课程

练习说明

The vectors income, percent_change, and p_values are available in your workspace.

  • First, compare the behavior of formatC() to format() by calling formatC() on x with format = "f" and digits = 1. This is the same vector you used with format(), do you see the difference?
  • Call formatC() on y with format = "f" and digits = 1. Notice how digits has consistent behavior regardless of the vector you format.
  • Format percent_change to one decimal place after the decimal point.
  • Format percent_change to one decimal place after the decimal point and add flag = "+". This forces the display of the sign.
  • Format p_values using format = "g" and digits = 2. This can be useful, since if there are any p-values in scientific notation, they must be < 0.0001.

交互式实操练习

通过完成这段示例代码来试试这个练习。

# 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
___
编辑并运行代码