Writing to the global environment from a function in R

前端 未结 1 1018
醉梦人生
醉梦人生 2021-01-15 15:15

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.

1条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-15 15:56

    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)
    

    0 讨论(0)
提交回复
热议问题