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