如何在 r 块选项中使用 if else 语句用默认图像替换丢失的图像

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"

假设我在 Rmardown 文件的参数中设置了以下文件路径。现在我为每个文件设置一个单独的块,如下所示:

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

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

现在假设我想编织文档,但我为 user2 指定的路径不可用。所以我更新了我的块并添加了以下内容,所以如果路径不可用或不正确,则不会评估该块。

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

我想做的是以某种方式指定文件是否不存在,然后从我在文件顶部的单独块中指定的默认路径上传另一张图片

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

所以基本上每当缺少文件路径时,我都想用这个默认图像替换它。任何帮助将不胜感激

在这种情况下,一个简单的 if-else 语句即可解决。如果你要运行它多次,将它打包成一个函数可能是值得的。

---
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)
```