从函数外部访问对象

时间:2015-10-08 16:35:33

标签: r function plot ggplot2

在绘图功能中,我指的是由更高级别的功能生成的对象,即我的绘图功能嵌套在更高级别的功能中。

代码排序如下:

minaverage <- seq(1:1440)

plot_minaverage <- function(minaverage){
  for_minaverage_plot.time <- rep(seq(1,1440),2)
  seq <- seq(start.time*60, length.out = 1440)
  minaverage_plot_time <- for_minaverage_plot.time[seq]

  minaverage_plot_df <- data.frame (minaverage_plot_time, minaverage)

  pp <- ggplot(minaverage_plot_df, aes(x=minaverage_plot_time, y = minaverage))+ 
 geom_bar(stat="identity", width = 1, position = position_dodge(width = 0.5))+
theme_bw()
print(pp)
}

我遇到的问题是minverage是在函数之外计算的,当我没有使用minaverage <<- minaverage将它存储在工作区中时,绘图函数无法访问它。

我如何访问minaverage?

1 个答案:

答案 0 :(得分:0)

您通过参数访问minaverage,这不是问题。

您的代码几乎可以使用,您只需要添加start.time作为参数,并且在倒数第二行中有拼写错误:

theme_bw()+

删除+以使其正常工作:

plot_minaverage = function(minaverage, start.time){
    for_minaverage_plot.time <- rep(seq(1,1440),2)
    seq <- seq(start.time*60, length.out = 1440)
    minaverage_plot_time <- for_minaverage_plot.time[seq]

    minaverage_plot_df <- data.frame (minaverage_plot_time, minaverage)

    pp <- ggplot(minaverage_plot_df, aes(x=minaverage_plot_time, y = minaverage))+
        geom_bar(stat="identity", width = 1, position = position_dodge(width = 0.5))+
        theme_bw()
    print(pp)
}