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!