表达式无法在函数内找到对象

问题描述 投票:0回答:2

如果在函数外部运行,下面的代码可以正常工作 - 所有内容都被正确评估,并且比较云可以转换为 ggplot。但是,当我想将其作为函数运行时,表达式无法再找到函数内定义的变量(例如,

term.matrix
)。

我尝试了一系列与

expression()
bquote()
expr()
等的组合,但一直无法找到解决方案。

有人可以帮助我吗?

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

r function expression r-environment
2个回答
0
投票

我认为这是与 Comparison.cloud 获取参数的环境有关的问题。它似乎是 .GlobalEnv 而不是由 cloud_as_ggplot() 创建的。

您可以通过将 term.matrix 设为全局变量来“修复”它,最后您可以删除它。对于我来说,它有点脏,但它有效。

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

-1
投票

这是旧的,但我有一个类似的问题,最终发现了这个:https://github.com/GuangchuangYu/ggplotify/issues/6#issuecomment-533442229,这为我解决了。

© www.soinside.com 2019 - 2024. All rights reserved.