FormattingStrings: Formatting Strings

FormattingStringsR Documentation

Formatting Strings

Description

Formatting codes for formatting strings follow the conventions of the base R strptime and sprintf functions. See below for further details.

Details

The fmtr packages accepts single strings as formatting specifications. These formatting strings are interpreted differently depending on the data type of the vector being formatted. For date and datetime vectors, the string will be interpreted as an input to the base R strptime function. For all other types of vectors, the formatting string will be interpreted as an input to the sprintf function.

The formatting codes for these functions are simple to use. For example, the code fapply(as.Date("1970-01-01"), "%B %d, %Y") will produce the output "January 01, 1970". The code fapply(1.2345, "%.1f") will produce the output "1.2".

Below are some commonly used formatting codes for dates:

  • %d = day as a number

  • %a = abbreviated weekday

  • %A = unabbreviated weekday

  • %m = month

  • %b = abbreviated month

  • %B = unabbreviated month

  • %y = 2-digit year

  • %Y = 4-digit year

  • %H = hour (24 hour clock)

  • %I = hour (12 hour clock)

  • %M = minute

  • %S = second

  • %p = AM/PM indicator

  • %q = Quarter as integer

  • %Q = Quarter as "Q?"

See the strptime function for additional codes and examples of formatting dates and times.

Below are some commonly used formatting codes for other data types:

  • %s = string

  • %d = integer

  • %f = floating point number

See the sprintf function for additional codes and examples of formatting other data types.

See Also

fapply for formatting vectors, and fdata for formatting data frames.

Examples

# Examples for formatting dates and times 
t <- Sys.time()
fapply(t, "%d/%m/%Y")              # Day/Month/Year
fapply(t, "%d%b%Y")                # Day abbreviated month year
fapply(t, "%y-%m")                 # Two digit year - month
fapply(t, "%A, %B %d")             # Weekday, unabbreviated month and date
fapply(t, "%Y-%Q")                 # Year and Quarter
fapply(t, "%Y-%m%-%d %H:%M:%S %p") # Common timestamp format

# Examples for formatting numbers
a <- 1234.56789
fapply(a, "%f")                    # Floating point number
fapply(a, "%.1f")                  # One decimal place
fapply(a, "%8.1f")                 # Fixed width
fapply(a, "%-8.1f")                # Fixed width left justified
fapply(a, "%08.1f")                # Zero padded
fapply(a, "%+.1f")                 # Forced sign
fapply(-a, "%+.1f")                # Negative 
fapply(a, "%.1f%%")                # Percentage
fapply(a, "$%.2f")                 # Currency
fapply(a, "The number is %f.")     # Interpolation

dbosak01/fmtr documentation built on June 15, 2024, 4:26 a.m.