---
title: "ox examples"
author: "Dawid Kałędkowski"
date: "12/9/2021"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{ox examples}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteDepends{checkmate, dplyr, magrittr}
  \usepackage[utf8]{inputenc}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

# Switching single value using `ox`

### Replace if `NULL`

```{r}
library(ox)
x <- NULL
y <- 1
  
# if (!is.null(x)) x else y
xo(is.null, x, .else = y)
```

### Replace if `infinite`
```{r}
library(ox)
x <- Inf
y <- 1
  
# if (is.finite(x)) x else y
xo(is.infinite, x, .else = y)
```

### Replace if `character(0)`
```{r}
x <- character(0)
y <- 1

# if (!identical(x, character(0))) x else y
xo(identical, x, character(0), .else = y)
```

### Replace if not class 
```{r}
x <- structure(0, class = "test")
y <- 1

# if (inherits(x, "test")) x else y
ox(inherits, x, "test", .else = y)
```

### Return larger value
```{r}
x <- 1
y <- 2

# if (x > y) x else y
ox(`>`, x, y)
```

### Replace if doesn't contain a text
```{r}
x <- "example text"
y <- "alternative text"

# if (grepl("text", x)) x else y
ox(grepl, "text", x, .else = y)
```

### if not a single character
```{r}
x <- c("a", "b")
y <- "a"

# if (is.character(x) && length(x) == 1) x else y
ox(function(x) is.character(x) && length(x) == 1, x, .else = y)
```

### combining with `checkmate`
```{r}
if (require(checkmate)) {
  x <- c("a", "b")
  y <- "a"
  
  # if (test_character(x, len = 2)) x else y
  ox(test_character, x, len = 2, .else = y)  
}
```

### using `magrittr` pipe
```{r}
library(magrittr)
x <- "a"
y <- 1

# x %<>% if (is.numeric(.)) . else y
x %<>% ox(.f = is.numeric, .else = y)
```
# Switching vector values using `OX`

### Replace `NA` with single value
```{r}
x <- c(1, NA, 3)
y <- 2

# x[is.na(x)] <- y[is.na(x)]
XO(is.na, x, .else = y)
```

### Replace minimum with value
```{r}
x <- c(1, 2, 3)
y <- 0

x[which.min(x)] <- y
XO(which.min, x, .else = y)
```


```{r}
```


### Get larger value from two vectors
```{r}
x <- c(1, 2, 3)
y <- c(4, 3, 2)

# x[x < y] <- y [x < y]
OX(`>`, x, y)
```

### Keep elements matching a condition
```{r}
x <- c(1, 2, 3, 4)

# x[x > 2]
OX(`>`, x, 2, .else = NULL)
```

### Keep list elements matching a condition
```{r}
x <- list(1, 2, 3, 4)

# x[vapply(x, function(xx) xx > 2, logical(1))]
OX(`>`, x, 2, .else = NULL)
```

### Replace values with `dplyr::mutate`
```{r}
library(dplyr)
iris %>%
  mutate(x = ifelse(Sepal.Length > Petal.Length, Sepal.Length, Petal.Length))

iris %>% mutate(x = OX(`>`, Sepal.Length, Petal.Length))
```
