表达式无法在函数内找到对象
如果在函数外部运行,下面的代码可以正常工作 - 所有内容都被正确评估,并且比较云可以转换为 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()
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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是旧的,但我有一个类似的问题,最终发现了这个: https: //github.com/GuangchuangYu/ggplotify/issues/6#issuecomment-533442229,这为我解决了这个问题。
以下是上面的代码,无需向全局环境分配任何内容:
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:
我认为这是与 Comparison.cloud 获取参数的环境有关的问题。它似乎是 .GlobalEnv 而不是由 cloud_as_ggplot() 创建的。
您可以通过将 term.matrix 设置为全局变量来“修复”它,最后您可以删除它。对于我来说,它有点脏,但很有效。
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.