Search code examples
rif-statementconditional-statementsr-markdownchunks

How to use if else statement in r chunk options to replace missing image with default image


title: File Reading
output: html_document
params:
  user1: "C:/Users/myDir/Desktop/apples.jpeg"
  user2:  "C:/Users/myDir/Desktop/oranges.jpeg"

Lets say I have the following file paths set in params in a Rmardown file. Now I set a separate chunk for each file as follows:

```{r}
image_read(params$user1)
```

```{r}
image_read(params$user2)
```

Now lets say I want to knit the document but the path I have specified for user2 is not available. So I updated my chunks and added the following so if path is not available or correct, the chunk is not evaluated.

```{r, eval = file.exists(params$user2)}
image_read(params$user2)

What I want to do is to somehow specify if file does not exist then upload another image from a default path that I have specified in a separate chunk at the top of my file

```{r}
default_image <- "C:/Users/myDir/Desktop/default.jpeg"
```

So essentially whenever a file path is missing, I want to replace it with this default image. Any help would be appreciated


Solution

  • In this case a simple if-else statement would solve it. If you are going to run it multiple times it might be worth it packing it into a function.

    ---
    title: "test conditional chunks"
    output: html_document
    params: 
      user1: "C:/Users/blah/Desktop/Discrete-event-simulation-concepts.png"
      user2: "C:/Users/blah/Desktop/Discrete-event-simulation-concepts5.png"
      default: "path_to_default"
    ---
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = TRUE)
    ```
    
    ```{r}
    library(magick)
    ```
    
    
    ```{r}
    # basic example
    if (file.exists(params$user1)) {
      image_read(params$user1)
    } else {
      image_read(params$default)
    }
    ```
    
    
    ```{r}
    # packing into a function
    image_read_with_default <- function(path, ...) {
      if (file.exists(params$user1)) {
        img <- magick::image_read(params$user1, ...)
      } else {
        img <- magick::image_read(params$default, ...)
      }
      
      return(img)
    }
    ```
    
    
    ```{r}
    image_read_with_default(params$user1)
    ```