The code below works fine if ran outside the function - everything is being evaluated correctly, and the comparison cloud can be converted to a ggplot. However, when I want to run this as a function, the expression can no longer find the variables that are defined inside the function (e.g., the term.matrix
).
I've tried a bunch of combinations with expression()
bquote()
expr()
etc., but have not been able to find the solution.
Can anyone help me?
library(tm)
library(ggplotify)
library(wordcloud)
library(ggplot2)
cloud_as_ggplot <- function(){
data(SOTU)
corp <- SOTU
corp <- tm_map(corp, removePunctuation)
corp <- tm_map(corp, content_transformer(tolower))
corp <- tm_map(corp, removeNumbers)
corp <- tm_map(corp, function(x)removeWords(x,stopwords()))
term.matrix <- TermDocumentMatrix(corp)
term.matrix <- as.matrix(term.matrix)
colnames(term.matrix) <- c("SOTU 2010","SOTU 2011")
cloud <- expression(
comparison.cloud(term.matrix,
max.words=40,
random.order=FALSE,
match.colors=TRUE))
title <- "as.ggplot is working"
ggplotify::as.ggplot(cloud) +
labs(title = title)
}
cloud_as_ggplot()