Search code examples
rpurrr

Problem rmarkdown Error in `map()`: In index: 1. Caused by error in `switch()`:


I need to parameterize my rmarkdown with two variables sys_loc_code and measurement_date. I tried as follows

index.RMD

title: " xxx - `r params$sys_loc_code` "
author: "xxx"
date: "2023-05-18"
format:
pdf:
  papersize: A3
  latex_engine: tinytex
  classoption: landscape
execute:
echo: false
df-print: kable
editor: visual
params:
   sys_loc_code: sys_loc_code
   measurement_date: measurement_date

render.R

purrr::walk(
.x = dados$sys_loc_code,
.y = dados$measurement_date,
~ rmarkdown::render(
input = "index.Rmd",
output_file = glue::glue("Checklist Agro - {.x}{.y}.pdf"),
params = list(sys_loc_code = {.x}, measurement_date = {.y})))

when running the render I get the following error message

Error in map():ℹ In index: 1.Caused by error in switch():! EXPR must be a length 1 vector

how to fix it?


Solution

  • purrr::walk does not take a .y argument, so the ~-function is seeing the whole vector at once. I think you need walk2:

    purrr::walk2(
      .x = dados$sys_loc_code,
      .y = dados$measurement_date,
      ~ rmarkdown::render(
          input = "index.Rmd",
          output_file = glue::glue("Checklist Agro - {.x}{.y}.pdf"),
          params = list(sys_loc_code = {.x}, measurement_date = {.y}))
    )
    

    For example,

    purrr::walk(.x = dados$a, .y = dados$b, .f = function(...) str(list(...)))
    # List of 2
    #  $   : int 1
    #  $ .y: int [1:3] 11 12 13
    # List of 2
    #  $   : int 2
    #  $ .y: int [1:3] 11 12 13
    # List of 2
    #  $   : int 3
    #  $ .y: int [1:3] 11 12 13
    purrr::walk2(.x = dados$a, .y = dados$b, .f = function(...) str(list(...)))
    # List of 2
    #  $ : int 1
    #  $ : int 11
    # List of 2
    #  $ : int 2
    #  $ : int 12
    # List of 2
    #  $ : int 3
    #  $ : int 13