Learn R Programming

fmtr (version 1.0.1)

fdata: Format a data frame or tibble

Description

The fdata function applies formatting attributes to the entire data frame.

Usage

fdata(x, ...)

Arguments

x

A data frame or tibble to be formatted.

...

Any follow-on parameters to the format function.

Value

A new, formatted data frame or tibble with the formats applied.

Details

If formats are assigned to the "format" attributes of the data frame columns, the fdata function will apply those formats to the specified columns, and return a new, formatted data frame. Formats can be specified as formatting strings, named vectors, user-defined formats, or vectorized formatting functions. The fdata function will apply the format to the associated column data using the fapply function. A format can also be specified as a formatting list of the previous four types. See the fapply function for additional information.

After formatting each column, the fdata function will call the base R format function on the data frame. Any follow on parameters will be sent to the format function.

See Also

fapply to apply a format to a vector, value to define a format object, fattr to assign formatting specifications to a single column/vector, and the formats, widths, and justification functions to get or set formatting for an entire data frame. Also see FormattingStrings for documentation on formatting strings.

Examples

Run this code
# NOT RUN {
## Example 1: Simple Formats ##
# Set up data frame
df <- mtcars[1:10, c("mpg", "cyl")]
df

# Define and assign formats
formats(df) <- list( mpg = value(condition(x >= 20, "High"),
                                condition(x < 20, "Low")),
                     cyl = value(condition(x == 4, "Small"),
                                condition(x == 6, "Midsize"),
                                condition(x == 8, "Large")))
              
# Apply formatting
fdata(df)

## Example 2: Formatting List ##
# Set up data
v1 <- c("num", "char", "date", "char", "date", "num")
v2 <- list(1.258, "H", Sys.Date(),
           "L", Sys.Date() + 60, 2.8865)

df <- data.frame(type = v1, values = I(v2))
df

# Create formatting list
lst <- flist(type = "row", lookup = v1, 
             num = "%.1f",
             char = value(condition(x == "H", "High"),
                          condition(x == "L", "Low"),
                          condition(TRUE, "NA")),
             date = "%d%b%y")

# Assign list and lookup to column attributes
df$values <- fattr(df$values, format = lst)

# Apply formatting list
fdata(df)
# }

Run the code above in your browser using DataLab