Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expression can't find object inside a function

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()

like image 247
Stefan Musch Avatar asked May 28 '26 17:05

Stefan Musch


1 Answers

This is old, but I had a similar question and ultimately came upon this: https://github.com/GuangchuangYu/ggplotify/issues/6#issuecomment-533442229, which solved it for me.

Here is the above code working without assigning anything to the global environment:

library(tm)
#> Loading required package: NLP
library(ggplotify)
library(wordcloud)
#> Loading required package: RColorBrewer
library(ggplot2)
#> 
#> Attaching package: 'ggplot2'
#> The following object is masked from 'package:NLP':
#> 
#>     annotate

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")
  
  title <- "as.ggplot is working"
  
  ggplotify::as.ggplot(
    function() comparison.cloud(term.matrix, max.words=40, random.order=FALSE, match.colors=TRUE)
  ) + 
    labs(title = title)
}

cloud_as_ggplot()

like image 76
Luther Blissett Avatar answered May 31 '26 06:05

Luther Blissett



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!