在R中,如何在图的两个内部函数之间传递数据帧/小节,然后保存图?

问题描述

我创建了一个外部函数来运行3个内部函数以进行数据预处理,然后绘制并保存它。

主要问题:将1个内部函数的数据框输出与下一个内部函数共享

library(tidyverse)
library(glue)

gapminder <- read.csv("https://raw.githubusercontent.com/swcarpentry/r-novice-gapminder/gh-pages/_episodes_rmd/data/gapminder-FiveYearData.csv")

外部功能

fn_run_all <-function(bench_country = India,year_start = 1952,year_end = 2007){
  
  
  year_start = year_start
  year_end = year_end
  
  # Function1 for PreProcess Benchmarked Country
  fn_benchmark_country({{bench_country}}) 

  # Function2 to PreProcess dates & pass df to function3 to plot  
  Plot_final <- fn_year_filter(gapminder_joined,year_start,year_end) %>% 
  
                # function 3 to plot  
                fn_create_plot(.,year_end,{{bench_country}})
  
  
  # Saving plot
  jpeg(file="gdp_benchmarked_FinalPlot.jpeg",width = 1400,height = 1800)
  Plot_final
  dev.off()
  
  # Printing Plot
  Plot_final
  }

fn_run_all(India,1952,2002)

问题1

如果我没有将第一个函数gapminder_joined的{​​{1}}的数据帧输出fn_benchmark_country(),那么函数2 global会出错。

但是当我将function1的输出fn_year_filter()推到gapminder_joined时,它就起作用了。

Global

Function1参考代码

Is it necessary to make it global even when I am returning it within the outer function or there is some other alternative way?

在上面的代码中,如果我取消注释第二行,那么它将起作用。

Function2参考代码

fn_benchmark_country  <- function(bench_country = India){
  
  bench_country = enquo(bench_country)

  gapminder_benchmarked_wider <- gapminder %>% 
                                  select(country,year,gdpPercap) %>% 
                                  pivot_wider(names_from = country,values_from = gdpPercap) %>% 
                                  arrange(year) %>% 
                                  # map_dbl( ~{.x - India })
                                  mutate(across(-1,~ . - !!bench_country))
                                  
  # Reshaping back to Longer
  gapminder_benchmarked_longer <- gapminder_benchmarked_wider %>% 
                                  pivot_longer(cols = !year,names_to = "country",values_to = "benchmarked") 
 
  # Joining tables
  gapminder_joined <- left_join(x = gapminder,y = gapminder_benchmarked_longer,by = c("year","country"))

  # converting to factor
  gapminder_joined$country <- as.factor(gapminder_joined$country)
  
  # gapminder_joined <<- gapminder_joined
  return(gapminder_joined)
}

解决方法

请勿从函数内部更新变量。您采用的方法是正确的,因此无需使用<<-,请保持fn_benchmark_country不变。尝试将返回的数据框保存在函数中。

fn_run_all <-function(bench_country = India,year_start = 1952,year_end = 2007){
  
  # Function1 for PreProcess Benchmarked Country
  gapminder_joined <- fn_benchmark_country({{bench_country}}) 
  # Function2 to PreProcess dates & pass df to function3 to plot  
  Plot_final <- fn_year_filter(gapminder_joined,year_start,year_end) %>% 
    # function 3 to plot  
   fn_create_plot(.,year_end,{{bench_country}})
   #...rest of the code
   #...
   #...
  
}