Examples of Predicate Functionals

Master R

By Guangming Lang Comment

A predicate is a function that returns a single TRUE or FALSE, for example, is.factor(), all(), or is.NULL(). A predicate functional is a function that applies a predicate to each element of a list or data frame. For example, we can define a predicate functional where() that checks the type of each column in a data frame.

where = function(f, x) {
        # Applies a predicate function to every element of a list or data frame.
        # f: a predicate function
        # x: a list or data frame
        #
        # Returns a logical vector.
        vapply(x, f, logical(1))
}

Here’s how you’d use it.

# make a example data frame
df = data.frame(x = 1:3, y = c("a", "b", "c"), z = c("Alex", "Bob", "Chris"))

# check if each column of the data frame is a factor
where(is.factor, df)
##     x     y     z 
## FALSE  TRUE  TRUE
# check if each column of the data frame is an integer
where(is.integer, df)
##     x     y     z 
##  TRUE FALSE FALSE
# check if each column of the data frame is a character
where(is.character, df)
##     x     y     z 
## FALSE FALSE FALSE

There’re 3 common predicate functionals already defined in base R, namely, Filter(), Find(), Position(). Here’s how you can use them.

# filter the factors in a data frame
subdf = Filter(is.factor, df)
subdf
##   y     z
## 1 a  Alex
## 2 b   Bob
## 3 c Chris
str(subdf) # note: Filter() returns a data frame
## 'data.frame':	3 obs. of  2 variables:
##  $ y: Factor w/ 3 levels "a","b","c": 1 2 3
##  $ z: Factor w/ 3 levels "Alex","Bob","Chris": 1 2 3
# find the 1st factor starting from the Left in a data frame
x_factor = Find(is.factor, df)
x_factor
## [1] a b c
## Levels: a b c
str(x_factor) # note: Find() returns the first factor it finds from the left
##  Factor w/ 3 levels "a","b","c": 1 2 3
# gives the position of the 1st factor starting from the Right in a data frame
Position(is.factor, df, right=T)
## [1] 3

This article is inspired by Hadley’s book “Advanced R”, you can buy it from Amazon or read it online for FREE.

If you enjoyed this post, get updates. It's FREE