如果没有错误的R函数不这样做,如何返回值

时间:2015-02-18 11:14:56

标签: r function null return-value

我的目标是将pyramid package生成的图表分配给列表。之后,我将把那个情节和其他人从列表中插入到文档中。但pyramid function似乎没有返回值。如何将金字塔图分配给对象?

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

同样,如果我将金字塔调用分配给我的列表,则没有任何反应。 pyramid返回的列表没有值。

plotlist2[["pyramid"]] <-  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")
> plotlist2[1]
[[1]]
NULL

我担心我在一些明显的错误理解中浮躁,所以我欢迎被正确设定。谢谢。

1 个答案:

答案 0 :(得分:2)

您可以使用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

根据您使用的图形设备,您可能必须使用dev.control(displaylist ="enable")启用显示列表才能生效