Learn R Programming

insight (version 0.20.4)

color_if: Color-formatting for data columns based on condition

Description

Convenient function that formats columns in data frames with color codes, where the color is chosen based on certain conditions. Columns are then printed in color in the console.

Usage

color_if(
  x,
  columns,
  predicate = `>`,
  value = 0,
  color_if = "green",
  color_else = "red",
  digits = 2
)

colour_if( x, columns, predicate = `>`, value = 0, colour_if = "green", colour_else = "red", digits = 2 )

Value

x, where columns matched by predicate are wrapped into color codes.

Arguments

x

A data frame

columns

Character vector with column names of x that should be formatted.

predicate

A function that takes columns and value as input and which should return TRUE or FALSE, based on if the condition (in comparison with value) is met.

value

The comparator. May be used in conjunction with predicate to quickly set up a function which compares elements in colums to value. May be ignored when predicate is a function that internally computes other comparisons. See 'Examples'.

color_if, colour_if

Character vector, indicating the color code used to format values in x that meet the condition of predicate and value. May be one of "red", "yellow", "green", "blue", "violet", "cyan" or "grey". Formatting is also possible with "bold" or "italic".

color_else, colour_else

See color_if, but only for conditions that are not met.

digits

Digits for rounded values.

Details

The predicate-function simply works like this: which(predicate(x[, columns], value))

Examples

Run this code
# all values in Sepal.Length larger than 5 in green, all remaining in red
x <- color_if(iris[1:10, ], columns = "Sepal.Length", predicate = `>`, value = 5)
x
cat(x$Sepal.Length)

# all levels "setosa" in Species in green, all remaining in red
x <- color_if(iris, columns = "Species", predicate = `==`, value = "setosa")
cat(x$Species)

# own function, argument "value" not needed here
p <- function(x, y) {
  x >= 4.9 & x <= 5.1
}
# all values in Sepal.Length between 4.9 and 5.1 in green, all remaining in red
x <- color_if(iris[1:10, ], columns = "Sepal.Length", predicate = p)
cat(x$Sepal.Length)

Run the code above in your browser using DataLab