-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathfunction-predicate.Rmd
46 lines (33 loc) · 1.33 KB
/
function-predicate.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# Predicate functions
```{r message = FALSE, warning = FALSE}
library(tidyverse)
```
Predicate functions are functions that return a single `TRUE` or `FALSE`. You use predicate functions to check if your input meets some condition. For example, `is.character()` is a predicate function that returns `TRUE` if its input is of type character and `FALSE` otherwise.
```{r}
is.character("a")
```
```{r}
is.character(4.5)
```
R does not have scalars. `"a"` is actually a character vector of length 1. `is.character()` and similar functions return a single value for all vectors, whether they have 1 element or many.
```{r}
x <- c("a", "b")
is.character(x)
```
In atomic vectors like `x`, all the elements must be the same type. The type of the individual elements will always be the same as the type of the atomic vector. You can use the function `typeof()` to find the type of a vector (or any other object in R).
```{r}
typeof(x)
```
`is.character()` simply checks whether `x` is of type character.
If the vector is not a character vector, `is.character()` will return `FALSE`.
```{r}
y <- c(1, 3)
typeof(y)
is.character(y)
```
Lists can have elements of any type. Even if all the elements of a list are of type character, the list is not a character vector, and `is.character()` will return `FALSE`.
```{r}
z <- list("a", "b")
typeof(z)
is.character(z)
```