Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/facebook/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从R中的函数写入全局环境_R - Fatal编程技术网

从R中的函数写入全局环境

从R中的函数写入全局环境,r,R,我是R新手,在理解如何处理本地和全球环境方面有些困难。我检查了局部变量和全局变量,但没有弄清楚 例如,如果我想使用一个函数绘制多个绘图,并按如下方式保存它们: PlottingFunction <- function(type) { type <<- mydata %>% filter(typeVariable==type) %>% qplot(a,b) } lapply(Lis

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

例如,如果我想使用一个函数绘制多个绘图,并按如下方式保存它们:

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

        lapply(ListOfTypes, PlottingFunction)

PlottingFunction无需将绘图指定给gloabl变量。所有绘图都可以保存在一个列表中

对于本例,我使用
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 = .)
}
现在,可以使用函数
do.call
来调用
grid.arrange
和列表
l
中的plot对象

do.call(grid.arrange, l)

我建议采用不同的方法供您考虑。使用mtcars的示例(其中
cyl
相当于您问题中的
typeVariable
):
res%groupby(cyl)%%>%do(plot=qplot(hp,mpg,data=);不可见(sapply(res$plot,print))
什么是
myData
?什么是
类型列表
?非常感谢!当我把它应用到我的实际数据中时,它也非常有效!
do.call(grid.arrange, l)