formats: Get or set formats for a data frame

View source: R/formats.R

formatsR Documentation

Get or set formats for a data frame

Description

The formats function extracts all assigned formats from a data frame, and returns them in a named list. The function also assigns formats from a named list.

Usage

formats(x)

formats(x) <- value

Arguments

x

A data frame or tibble

value

A named list of formats

Details

If formats are assigned to the "format" attributes of the data frame columns, the formats function will extract those formats. The function will return the formats in a named list, where the names correspond to the name of the column that the format was assigned to. If a column does not have a format attribute assigned, that column will not be included in the list.

When used on the receiving side of an assignment, the function will assign formats to a data frame. The formats should be in a named list, where each name corresponds to the data frame column to assign the format to.

The formats function can also accept a format catalog as input. This feature allows you to save formats in metadata, load them into a format catalog, and quickly assign them to a data frame or tibble. See the fcat function for additional information.

Finally, if you wish to clear out format attributes, assign a NULL value to the formats function.

Value

A named list of formats.

See Also

fdata to display formatted data, value to create user-defined formats, fapply to apply formats to a vector, and fcat to create a format catalog. Also see FormattingStrings for documentation on formatting strings.

Examples

# Take subset of data
df1 <- mtcars[1:10, c("mpg", "cyl") ]

# Print current state
print(df1)

# Assign formats
attr(df1$mpg, "format") <- value(condition(x >= 20, "High"),
                                 condition(x < 20, "Low"))
attr(df1$cyl, "format") <- function(x) format(x, nsmall = 1)

# Display formatted data
fdata(df1)

# Extract format list
lst <- formats(df1)

# Alter format list and reassign
lst$mpg <- value(condition(x >= 22, "High"),
                 condition(x < 22, "Low"))
lst$cyl <- function(x) format(x, nsmall = 2)
formats(df1) <-  lst

# Display formatted data
fdata(df1)

# Clear formats
formats(df1) <- NULL

# Confirm formats are cleared 
formats(df1)

fmtr documentation built on Nov. 10, 2023, 9:07 a.m.