Search code examples
rpagedownr-glue

Is there a way to suppress glue output in R, if the variable is empty?


I am creating a resume using pagedown. It takes a data.frame of CV inputs and generates a pagedown HTML output via glue package. However, if the variable is empty (as in the example below), glue generates a blank line. How can I prevent this behavior and suppress the line break?

Note: I can replace the NA or NULL values with empty strings, but it will still create a line break. I want to remove the line break (or new line) when the variable is NA.

library(glue)
library(tibble)

glue_template <- "
  ### 
  {title}
  
  {loc}
  
  {company}
"

dat = tribble(
  ~title,    ~loc,    ~company,
  "intern",  "seattle", "escience",
  "intern",  NA,        "posit" 
)

This is the current output:

print(glue_data(dat, glue_template, .na = ""))
#> ### 
#> intern
#> 
#> seattle
#> 
#> escience
#> ### 
#> intern
#> 
#>
#> 
#> posit

This is the desired output:

print(glue_data(dat, glue_template, .na = ""))
#> ### 
#> intern
#> 
#> seattle
#> 
#> escience
#> ### 
#> intern
#> 
#> posit

Created on 2023-01-06 with reprex v2.0.2

Session info:

sessionInfo()
#> R version 4.2.1 (2022-06-23)
#> Platform: x86_64-apple-darwin17.0 (64-bit)
#> Running under: macOS Big Sur ... 10.16
#> 
#> Matrix products: default
#> BLAS:   /Library/Frameworks/R.framework/Versions/4.2/Resources/lib/libRblas.0.dylib
#> LAPACK: /Library/Frameworks/R.framework/Versions/4.2/Resources/lib/libRlapack.dylib
#> 
#> locale:
#> [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
#> 
#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base     
#> 
#> other attached packages:
#> [1] tibble_3.1.8 glue_1.6.2  
#> 
#> loaded via a namespace (and not attached):
#>  [1] rstudioapi_0.13 knitr_1.39      magrittr_2.0.3  rlang_1.0.4    
#>  [5] fastmap_1.1.0   fansi_1.0.3     stringr_1.4.0   highr_0.9      
#>  [9] tools_4.2.1     xfun_0.31       utf8_1.2.2      cli_3.3.0      
#> [13] withr_2.5.0     htmltools_0.5.3 yaml_2.3.5      digest_0.6.29  
#> [17] lifecycle_1.0.1 crayon_1.5.1    vctrs_0.4.1     fs_1.5.2       
#> [21] evaluate_0.15   rmarkdown_2.14  reprex_2.0.2    stringi_1.7.8  
#> [25] compiler_4.2.1  pillar_1.8.0    pkgconfig_2.0.3

Solution

  • You can use a simple transformer and alter your template somewhat. This will ensure you don't have extra spacing whenever NULL is encountered.

    glue_template <- "###
    {title}{loc}{company}
    "
    
    null_transformer <- function(text, envir) {
      if (text == "company") {
        res <- eval(parse(text = text), envir)
        ifelse(res == "NULL", "", paste0(res))
      } else {
        res <- eval(parse(text = text), envir)
        ifelse(res == "NULL", "", paste0(res, "\n\n"))
      }
    }
    
    glue_data(dat, glue_template, .transformer = null_transformer)
    

    Gives:

    ###
    intern
    
    seattle
    
    escience
    ###
    intern
    
    posit