Expression can't find object inside a function

151 Views Asked by At

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

1

There are 1 best solutions below

3
On

I think it is an issue about the environment from which comparison.cloud is taking the parameters. It seems to be .GlobalEnv and not the one created by cloud_as_ggplot().

You can "fix" it by making term.matrix a global variable and at the end you can delete it. For my it is kind of dirty but it works.

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"
  p<-ggplotify::as.ggplot(cloud) + 
    labs(title = title)
  rm(term.matrix,envir=.GlobalEnv)
  p
}

cloud_as_ggplot()