如果无错误的R函数不返回值,如何返回该值

如果无错误的R函数不返回值,如何返回该值,r,function,null,return-value,R,Function,Null,Return Value,我的目标是将金字塔包生成的绘图分配给列表。稍后,我将把该绘图和其他绘图从列表中插入到文档中。但是金字塔函数似乎不返回值。如何将棱锥图指定给对象 install.packages("pyramid") # functions to draw a population pyramid library(pyramid) # create a mock data frame to comparing this plot to a counterpart from plotrix df <- d

我的目标是将
金字塔包生成的绘图分配给列表。稍后,我将把该绘图和其他绘图从列表中插入到文档中。但是
金字塔函数
似乎不返回值。如何将棱锥图指定给对象

install.packages("pyramid") # functions to draw a population pyramid
library(pyramid)

# create a mock data frame to comparing this plot to a counterpart from plotrix

df <- data.frame(level1 = c(9,9,4,3,34,28), levelsame = c(9,9,4,3,34,28),
 title = c("Dir", "Exec. Dir", "Mgr", "Sr. Mgr", "Mgt Princ", "EVP+"))

        # assign the plot (hopefully) to an object
empty <- pyramid(df, Laxis = seq(1,35,5), AxisFM = "g", Csize = 0.8, Cgap = .5, Llab = "",
                                 Rlab = "", Clab = "Title", GL = F, Lcol = "blue", Rcol = "blue",
                                 Ldens = -1, main = "Distribution of Levels")

> empty
NULL

我担心我在一些明显的错误理解中犯了错误,所以我欢迎被纠正。谢谢。

您可以使用
recordPlot()
函数将当前绘图保存到变量中

在您的情况下,您可以:

#print the plot
pyramid(df, Laxis = seq(1,35,5), AxisFM = "g", Csize = 0.8, Cgap = .5, Llab = "",
        Rlab = "", Clab = "Title", GL = F, Lcol = "blue", Rcol = "blue",
        Ldens = -1, main = "Distribution of Levels")

#save the current printed plot
pyrPlot<-recordPlot()

#plot it again
pyrPlot
#打印绘图
金字塔(df,Laxis=seq(1,35,5),AxisFM=“g”,Csize=0.8,Cgap=0.5,Llab=”,
Rlab=“”,Clab=“Title”,GL=F,Lcol=“blue”,Rcol=“blue”,
Ldens=-1,main=“级别分布”)
#保存当前打印的绘图

也许您可以尝试使用
trace
函数或
fix(pyramid)
将一些代码添加到
pyramid
函数中,这是我的两个新函数,谢谢。我试过fix(),但trace的语法是什么?太好了!我不知道recordPlot()。顺便说一句,对于函数不返回值的其他情况,是否有类似recordTable()或recordVariable()的等价项?如果函数在控制台中打印内容,您可以查看
capture.output(…)
#print the plot
pyramid(df, Laxis = seq(1,35,5), AxisFM = "g", Csize = 0.8, Cgap = .5, Llab = "",
        Rlab = "", Clab = "Title", GL = F, Lcol = "blue", Rcol = "blue",
        Ldens = -1, main = "Distribution of Levels")

#save the current printed plot
pyrPlot<-recordPlot()

#plot it again
pyrPlot