1

not sure what the cause of the problem is here...

Code works when I inline the function, but not when I call the function...

Works:

library(officer)
data <- data.frame(test=c(1:10),test2=rep(c("a","b"),5))

doc <- read_docx()

# Inlined function
tabledata <- data$test2
d <- table(tabledata)
doc <-body_add_plot(doc, value = plot_instr(code = {barplot(d)}))


print(doc,target="test.docx")

Doesn't work:

library(officer)
data <- data.frame(test=c(1:10),test2=rep(c("a","b"),5))

doc <- read_docx()

createBarPlot <- function(){

    tabledata <- data$test2

    d <- table(tabledata)

    doc <-body_add_plot(doc, value = plot_instr(code = {barplot(d)}))
 
}

createBarPlot()

print(doc,target="test.docx")

error message:

Error in barplot(d) : object 'd' not found
Calls: createBarPlot ... tryCatch -> tryCatchList -> eval -> eval -> barplot
Backtrace:
    █
 1. └─global::createBarPlot()
 2.   └─officer::body_add_plot(...)
 3.     ├─base::tryCatch(...)
 4.     │ └─base:::tryCatchList(expr, classes, parentenv, handlers)
 5.     ├─base::eval(value$code)
 6.     │ └─base::eval(value$code)
 7.     └─graphics::barplot(d)
Execution halted

Any idea why putting this code inside a function causes it to fail?

Edit: So after @Lmc's suggestion in the comments I changed the line where I assign d to d <<- table(tabledata) - and it worked! It does kind of make sense to me, as doc (which is a global) is modified but doesn't have access to d. But if someone can/wants to explain in more detail I'd be happy to learn!

Tschösi
  • 491
  • 3
  • 13
  • 1
    I don't know if this will solve your issue because I am having an error loading the latest version of `officer`, but you might have a scoping problem. In your function you are making an assignment to an object `doc`, but I am assuming you want to change the object `doc` that you created in your `.GlobalEnv`. The `doc` object you're creating with `body_add_plot` lives within your function environment. You might want to try `doc <<- body_add_plot(...)`. For more information see `?"<<-"`. – LMc Mar 02 '21 at 21:34
  • @LMc Good catch! It seems the problem was that I had to "deep assign" (or whatever `<<-` is called) `d`. So changing it to `d <<- table(tabledata)` did the trick! Thanks! – Tschösi Mar 02 '21 at 21:38

0 Answers0