yoland
yoland

Reputation: 554

Writing to the global environment from a function in R

Im new to R and have some trouble understanding how to handle local and global environments. I checked the Post on local and global variables, but couldn't figure it out.

If, for example, I would like to make several plots using a function and save them like this:

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

        lapply(ListOfTypes, PlottingFunction)

Which didn't yield the desired result. I tried using the assign() function, but couldn't get it to work either.

I want to save the graphs in the global environment so I can combine them using gridExtra. This might not be the best way to do that, but I think it might be useful to understand this issue nevertheless.

Upvotes: 2

Views: 674

Answers (1)

Sven Hohenstein
Sven Hohenstein

Reputation: 81683

You don't need to assign the plot to a gloabl variable. All plots can be saved in one list.

For this example, I use the iris data set.

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 ...

The modified function without assignment:

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

One figure per Species is created

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

l <- lapply(species, PlottingFunction)

Now, the function do.call can be used to call grid.arrange with the plot objects in the list l.

do.call(grid.arrange, l)

enter image description here

Upvotes: 3

Related Questions