将打印另存为R对象并显示在栅格中

将打印另存为R对象并显示在栅格中,r,function,ggplot2,r-grid,R,Function,Ggplot2,R Grid,在下面的可复制示例中,我尝试为ggplot分布图创建一个函数,并将其保存为R对象,目的是在网格中显示两个图 ggplothist<- function(dat,var1) { if (is.character(var1)) { var1 <- which(names(dat) == var1) } distribution <- ggplot(data=dat, aes(dat[,var1])) distrib

在下面的可复制示例中,我尝试为ggplot分布图创建一个函数,并将其保存为R对象,目的是在网格中显示两个图

ggplothist<- function(dat,var1)
{
        if (is.character(var1)) {
            var1 <- which(names(dat) == var1) 
    }
    distribution <- ggplot(data=dat, aes(dat[,var1])) 
    distribution <- distribution  + geom_histogram(aes(y=..density..),binwidth=0.1,colour="black", fill="white")
    output<-list(distribution,var1,dat)
    return(output)
}

我得到和以前一样的分配? 但是,如果我使用函数中包含的信息,请将其返回并将其重置为全局变量

var1=as.numeric(output1[2]);dat=as.data.frame(output1[3]);p1 <- output1[1]
p1
将产生相同的错误

gList(列表)中的错误(列表)绘图=列表(数据=列表)x=c(9.66707664902549,: “gList”中只允许“grobs”

作为最后一次尝试,我尝试使用recordPlot()将绘图的所有内容记录到一个对象中

    ggplothist<- function(dat,var1)
{
    if (is.character(var1)) {
            var1 <- which(names(dat) == var1) 
    }
    distribution <- ggplot(data=dat, aes(dat[,var1])) 
    distribution <- distribution  + geom_histogram(aes(y=..density..),binwidth=0.1,colour="black", fill="white")
    plot(distribution)
    distribution<-recordPlot()
    output<-list(distribution,var1,dat)
    return(output)
}
ggplothist找到了解决方案

插入

localenv <- environment() 

localenv您需要使用双括号而不是单括号从列表中提取元素:例如,
p1=output1[[1]]
。如果这是您所需要的,您可能一直在寻找使用ggplot2生成函数的
aes_string
。我更喜欢生成一个代码,可以获取任何输入数据,然后将其重新格式化为适合函数其余部分的任何格式,如果(is.character(var1)){var1似乎我的核心假设是R在每次函数调用时更新dat和var1变量,并在局部函数环境中使用该变量,而不是在函数外部使用全局环境。
var1=as.numeric(output1[2]);dat=as.data.frame(output1[3]);p1 <- output1[1]
p1
 var1=as.numeric(output2[2]);dat=as.data.frame(output2[3]);p2 <- output2[1]
 grid.arrange(p1,p2)
 ggplothist<- function(dat,var1)
{
    if (is.character(var1)) {
            var1 <- which(names(dat) == var1) 
    }
    distribution <- ggplot(data=dat, aes(dat[,var1])) 
    distribution <- distribution  + geom_histogram(aes(y=..density..),binwidth=0.1,colour="black", fill="white")
    plot(distribution)
    pltlist <- list()
    pltlist[["plot"]] <- distribution
    output<-list(pltlist,var1,dat)
    return(output)
}

output1 <- ggplothist(dat=df,var1='x')
p1<-output1[1]

output2 <- ggplothist(dat=df2,var1='y')
p2<-output2[1]

output1[1]
grid.arrange(p1,p2)
    ggplothist<- function(dat,var1)
{
    if (is.character(var1)) {
            var1 <- which(names(dat) == var1) 
    }
    distribution <- ggplot(data=dat, aes(dat[,var1])) 
    distribution <- distribution  + geom_histogram(aes(y=..density..),binwidth=0.1,colour="black", fill="white")
    plot(distribution)
    distribution<-recordPlot()
    output<-list(distribution,var1,dat)
    return(output)
}
localenv <- environment() 
distribution <- ggplot(data=dat, aes(dat[,var1]),environment = localenv)