【问题标题】:Writing to the global environment from a function in R从 R 中的函数写入全局环境
【发布时间】:2016-03-27 15:46:15
【问题描述】:

我是 R 新手,在理解如何处理本地和全局环境方面有些困难。我检查了局部和全局变量上的Post,但无法弄清楚。

例如,如果我想使用一个函数绘制多个图并像这样保存它们:

PlottingFunction <- function(type) {
        type <<- mydata %>% 
        filter(typeVariable==type) %>%
        qplot(a,b)
          }

        lapply(ListOfTypes, PlottingFunction)

这没有产生预期的结果。我尝试使用 assign() 函数,但也无法正常工作。

我想将图形保存在全局环境中,以便可以使用 gridExtra 组合它们。这可能不是最好的方法,但我认为理解这个问题可能还是有用的。

【问题讨论】:

  • 我建议您考虑另一种方法。使用 mtcars 的示例(其中cyl 相当于您的问题中的typeVariable):res &lt;- mtcars %&gt;% group_by(cyl) %&gt;% do(plot = qplot(hp, mpg, data = .)); invisible(sapply(res$plot, print))
  • 什么是myDataListOfTypes 是什么?

标签: r


【解决方案1】:

您不需要将绘图分配给全局变量。所有绘图都可以保存在一个列表中。

对于这个例子,我使用iris 数据集。

library(gridExtra)
library(ggplot2)
library(dplyr)

str(iris)
# 'data.frame': 150 obs. of  5 variables:
#  $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
#  $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
#  $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
#  $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
#  $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...

没有赋值的修改函数:

PlottingFunction <- function(type) {
  iris %>% 
    filter(Species == type) %>%
    qplot(Sepal.Length, Sepal.Width, data = .)
}

每个Species 创建一个图

species <- unique(iris$Species)
# [1] setosa     versicolor virginica 
# Levels: setosa versicolor virginica    

l <- lapply(species, PlottingFunction)

现在,函数do.call 可用于调用grid.arrange 与列表中的绘图对象l

do.call(grid.arrange, l)

【讨论】:

  • 非常感谢!这非常有效,当我将它应用到我的实际数据时也是如此!
猜你喜欢
  • 1970-01-01
  • 2020-07-24
  • 2017-11-05
  • 2016-04-22
  • 1970-01-01
  • 2022-11-02
  • 2012-10-20
  • 2018-02-16
  • 1970-01-01
相关资源
最近更新 更多