Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Figure Error in if (grepl("docx", opts_knit$get("rmarkdown.pandoc.to"))) {: argument is of length zero #1

Open
ahbon123 opened this issue Nov 2, 2021 · 4 comments

Comments

@ahbon123
Copy link

ahbon123 commented Nov 2, 2021

Hello, I get an error: Figure Error in if (grepl("docx", opts_knit$get("rmarkdown.pandoc.to"))) {: argument is of length zero, while running analysis part, could you help?

@KWigg4
Copy link

KWigg4 commented Jun 10, 2022

I did too - did you figure it out, abhon123?

@KWigg4
Copy link

KWigg4 commented Jun 10, 2022

UPDATE: I got the error when I ran the code in rmd, but when I knitted it, it worked fine! Who knows?!

@pvsundar
Copy link

pvsundar commented Jul 29, 2023

I too get this message:


Figure Error in if (grepl("docx", opts_knit$get("rmarkdown.pandoc.to"))) { :
argument is of length zero

`# Analysis

# this chunk will programmatically generates Markdown code (results='asis')
# split the data by specie to simulate different attributes to analyze, it is here 3 here but it could be any number.
data <- split(iris, iris$Species)
uniqueSpecies <- levels(iris$Species)
# for loop
for(i in 1:length(uniqueSpecies)){
  
  dataSubset <- data[[uniqueSpecies[i]]]
    
  # print the heading
  cat("\n##", uniqueSpecies[i], "\n")
  
  # print an empty line
  cat("\n  <br>  \n")
  
  # print some text
  cat("Figure ")
  # reference the figure below (note the use of knit_print_run function in 'asis' chunks)
  knit_print_run(run_reference(paste0("pData", uniqueSpecies[i])))
  cat(" shows the relation between Sepal width and length.")
  
  # plot the data 
  pData <- ggplot(aes(x=Sepal.Length, y=Sepal.Width), data=dataSubset) + 
    geom_point() + geom_smooth(method='lm', se=F) + labs(title=uniqueSpecies[i])
  
  # output the plot (note the use of the print function in 'asis' chunks)
  print(pData)
  
  cat("\n") # sometimes you need to add this to make things work
  
  # Add the figure numbering and caption (note the use of the knit_print_block function in 'asis' chunks)
  fig_num <- run_autonum(seq_id = "Figure", pre_label = "Figure ", bkm = paste0("pData", uniqueSpecies[i]))
  knit_print_block(block_caption(paste0("Scatter plot of Sepal Width vs Sepal Length for ", uniqueSpecies[i], ". Blue line is a linear regression."),
              style = "caption", autonum = fig_num))
  
  
  # print some text
  cat("A linear regression was performed using Sepal.Length as the response and Sepal.Width as the explanatory variable. Table ")
  knit_print_run(run_reference(paste0("tabRegression", uniqueSpecies[i])))
  cat(" shows the parameters estimates and 95% Confidence intervals.")
  
  cat("\n") # sometimes you need to add this to make things work
  
  # do a regression generate the fit summary table
  regression <- lm(Sepal.Length ~ Sepal.Width, data=dataSubset, digits = 4)
  tabRegression <- tidy(regression)
  tabRegression <- cbind(tabRegression, confint(regression, level=0.95))
  
  # Add the table numbering and caption (note the use of the knit_print_block function in 'asis' chunks)
  tab_num <- run_autonum(seq_id = "Table", pre_label = "Table ", bkm = paste0("tabRegression", uniqueSpecies[i]))
  knit_print_block(block_caption(paste0("Parameters estimates of the fit for ", uniqueSpecies[i]),
              style = "caption", autonum = tab_num))
  
  
  
  # output the summary table (note the use of knit_print and cat functions in 'asis' chunks)
  tabRegression %>% flextable() %>% 
     colformat_double(digits = 4)%>% knit_print() %>% cat()
  
  cat('\n')
}
# Add a page break
run_pagebreak()

@pvsundar
Copy link

I too get this message: Figure Error in if (grepl("docx", opts_knit$get("rmarkdown.pandoc.to"))) { : argument is of length zero

`# Analysis

# this chunk will programmatically generates Markdown code (results='asis')
# split the data by specie to simulate different attributes to analyze, it is here 3 here but it could be any number.
data <- split(iris, iris$Species)
uniqueSpecies <- levels(iris$Species)
# for loop
for(i in 1:length(uniqueSpecies)){
  
  dataSubset <- data[[uniqueSpecies[i]]]
    
  # print the heading
  cat("\n##", uniqueSpecies[i], "\n")
  
  # print an empty line
  cat("\n  <br>  \n")
  
  # print some text
  cat("Figure ")
  # reference the figure below (note the use of knit_print_run function in 'asis' chunks)
  knit_print_run(run_reference(paste0("pData", uniqueSpecies[i])))
  cat(" shows the relation between Sepal width and length.")
  
  # plot the data 
  pData <- ggplot(aes(x=Sepal.Length, y=Sepal.Width), data=dataSubset) + 
    geom_point() + geom_smooth(method='lm', se=F) + labs(title=uniqueSpecies[i])
  
  # output the plot (note the use of the print function in 'asis' chunks)
  print(pData)
  
  cat("\n") # sometimes you need to add this to make things work
  
  # Add the figure numbering and caption (note the use of the knit_print_block function in 'asis' chunks)
  fig_num <- run_autonum(seq_id = "Figure", pre_label = "Figure ", bkm = paste0("pData", uniqueSpecies[i]))
  knit_print_block(block_caption(paste0("Scatter plot of Sepal Width vs Sepal Length for ", uniqueSpecies[i], ". Blue line is a linear regression."),
              style = "caption", autonum = fig_num))
  
  
  # print some text
  cat("A linear regression was performed using Sepal.Length as the response and Sepal.Width as the explanatory variable. Table ")
  knit_print_run(run_reference(paste0("tabRegression", uniqueSpecies[i])))
  cat(" shows the parameters estimates and 95% Confidence intervals.")
  
  cat("\n") # sometimes you need to add this to make things work
  
  # do a regression generate the fit summary table
  regression <- lm(Sepal.Length ~ Sepal.Width, data=dataSubset, digits = 4)
  tabRegression <- tidy(regression)
  tabRegression <- cbind(tabRegression, confint(regression, level=0.95))
  
  # Add the table numbering and caption (note the use of the knit_print_block function in 'asis' chunks)
  tab_num <- run_autonum(seq_id = "Table", pre_label = "Table ", bkm = paste0("tabRegression", uniqueSpecies[i]))
  knit_print_block(block_caption(paste0("Parameters estimates of the fit for ", uniqueSpecies[i]),
              style = "caption", autonum = tab_num))
  
  
  
  # output the summary table (note the use of knit_print and cat functions in 'asis' chunks)
  tabRegression %>% flextable() %>% 
     colformat_double(digits = 4)%>% knit_print() %>% cat()
  
  cat('\n')
}
# Add a page break
run_pagebreak()

This is test of an excellent example by : Thomas de Marchin - Awesome Rmarkdown Word report with programmatically inserted headings, outputs and cross-references

Very Intriguingly, I can get it to work in a local drive where I installed all the libraries earlier today.
When I copy the .RMD file to another location and try to get it to run there i got the above error.
So, I opened the .Rmd file in the same PROJECT and I could get it to work only if I copied one of the outputs: grateful-refs.
Anyway, it may be a useful template to have for others that also uses the GRATEFUL package to cite sources used.

CODE:
--- title: "Thomas de Marchin - Awesome Rmarkdown Word report with programmatically inserted headings, outputs and cross-references" author: "P.V. (SUNDAR) Balakrishnan" date: "r Sys.time()`"
output:
html_document:
toc: yes
toc_depth: 2
fig_caption: yes
number_sections: yes
officedown::rdocx_document:
mapstyles:
Normal: First Paragraph
bibliography: grateful-refs.bib

# Let's setup a few things.
rm(list=ls())
library(knitr)
library(officedown)
library(officer)
library(ggplot2)
library(tidyverse)
library(broom)
library(flextable)
# set chunks defaults
# set flextable defaults

knitr::opts_chunk$set(
	echo = TRUE,
	message = FALSE,
	warning = FALSE
)
  set_flextable_defaults(
  font.family = "Calibri", font.size = 9, 
  theme_fun = "theme_vanilla",
  big.mark="", table.layout="autofit")
  
# formatting properties for specific paragraphs
centeredP <- fp_par(text.align = "center")

ft <- fp_text(shading.color='#EFEFEF', bold = TRUE)
fp <- fp_par(
  text.align = "center", 
  padding.bottom = 20, padding.top = 120, 
  border.bottom = fp_border())

This document presents most of the features of the package r ftext("officedown", ft). r fp

\newpage

Introduction

The aim of this document is to introduce a way to generate word reports from R using Rmarkdown with programmatically inserted headings, outputs and Word cross-references.

See https://towardsdatascience.com/awesome-r-markdown-word-report-with-programmatically-inserted-headings-outputs-and-19ad0de29a22 to understand the context of this example.

# this chunk is a normal chunk compared to the next one
# create the bookmark for the summary table
tab_num <- run_autonum(seq_id = "Table", pre_label = "Table ", bkm = "summaryTable")
# add the caption
block_caption(label= "Summary table for the iris dataset",
              style = "caption", autonum = tab_num)
# create the summary table and output it with flextable()
summaryData <- iris %>% gather(value="value", key="Attribute", -Species) %>% group_by(Attribute, Species) %>% summarise(n=n(), mean=mean(value), sd=sd(value), min=min(value), max=max(value)) 
summaryData %>% flextable() %>% merge_v(j = "Attribute") %>% colformat_double(j=c("mean", "sd"), digits = 2)

\newpage

Analysis

# this chunk will programmatically generates Markdown code (results='asis')
# split the data by specie to simulate different attributes to analyze, it is here 3 here but it could be any number.
data <- split(iris, iris$Species)
uniqueSpecies <- levels(iris$Species)
# for loop
for(i in 1:length(uniqueSpecies)){
  
  dataSubset <- data[[uniqueSpecies[i]]]
    
  # print the heading
  cat("\n##", uniqueSpecies[i], "\n")
  
  # print an empty line
  cat("\n  <br>  \n")
  
  # print some text
  cat("Figure ")
  # reference the figure below (note the use of knit_print_run function in 'asis' chunks)
  knit_print_run(run_reference(paste0("pData", uniqueSpecies[i])))
  cat(" shows the relation between Sepal width and length.")
  
  # plot the data 
  pData <- ggplot(aes(x=Sepal.Length, y=Sepal.Width), data=dataSubset) + 
    geom_point() + geom_smooth(method='lm', se=F) + labs(title=uniqueSpecies[i])
  
  # output the plot (note the use of the print function in 'asis' chunks)
  print(pData)
  
  cat("\n") # sometimes you need to add this to make things work
  
  # Add the figure numbering and caption (note the use of the knit_print_block function in 'asis' chunks)
  fig_num <- run_autonum(seq_id = "Figure", pre_label = "Figure ", bkm = paste0("pData", uniqueSpecies[i]))
  knit_print_block(block_caption(paste0("Scatter plot of Sepal Width vs Sepal Length for ", uniqueSpecies[i], ". Blue line is a linear regression."),
              style = "caption", autonum = fig_num))
  
  
  # print some text
  cat("A linear regression was performed using Sepal.Length as the response and Sepal.Width as the explanatory variable. Table ")
  knit_print_run(run_reference(paste0("tabRegression", uniqueSpecies[i])))
  cat(" shows the parameters estimates and 95% Confidence intervals.")
  
  cat("\n") # sometimes you need to add this to make things work
  
  # do a regression generate the fit summary table
  regression <- lm(Sepal.Length ~ Sepal.Width, data=dataSubset, digits = 4)
  tabRegression <- tidy(regression)
  tabRegression <- cbind(tabRegression, confint(regression, level=0.95))
  
  # Add the table numbering and caption (note the use of the knit_print_block function in 'asis' chunks)
  tab_num <- run_autonum(seq_id = "Table", pre_label = "Table ", bkm = paste0("tabRegression", uniqueSpecies[i]))
  knit_print_block(block_caption(paste0("Parameters estimates of the fit for ", uniqueSpecies[i]),
              style = "caption", autonum = tab_num))
  
  
  
  # output the summary table (note the use of knit_print and cat functions in 'asis' chunks)
  tabRegression %>% flextable() %>% 
     colformat_double(digits = 4)%>% knit_print() %>% cat()
  
  cat('\n')
}
# Add a page break
run_pagebreak()

Conclusion

\newpage

REFERENCES

library(report)
renv::snapshot()

r <- report_text(sessionInfo())
summary(r)  
     # # Add a page break
     run_pagebreak()

             ###citations
library(grateful)
#nocite_references(cite_packages(output = "citekeys", out.dir = "."))
# cite_packages(output = "file",
#               cite.tidyverse = TRUE,
#               include.RStudio = TRUE,
#               out.file = "grateful-references", 
#               out.dir = ".")
# # Add a page break
# run_pagebreak()

pkgs <- cite_packages(output = "table", out.dir = ".")

knitr::kable(pkgs)

`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants