Home > OS >  Download data and add to Glob.Env
Download data and add to Glob.Env

Time:11-11

I wrote a loop to download files from a public ftp server using the function get_pnadc like:

for (i in 2012:2013){
  for (a in 1:4){
    get_pnadc(year=i, quarter=a,  vars=c("VD4001","VD4002"),
                                 labels=TRUE, deflator=TRUE, design=FALSE,
                                   savedir = 'Microdados/')        
  }
}

I would like to have one object for each quarter/year also in my Global Environment. Is this possible to add such a command in my loop?

CodePudding user response:

As mentioned, consider saving a list of objects which you can do so by generalizing your retrieval and build a list of names with expand.grid, Map (wrapper to mapply), and paste0.

proc_data <- function(i, a)
  get_pnadc(
     year=i, quarter=a, vars=c("VD4001","VD4002"),
     labels=TRUE, deflator=TRUE, design=FALSE,
     savedir = 'Microdados/'
  )
)
# CREATE DATA FRAME OF INPUT PARAMS
params_df <- expand.grid(quarter = 1:4, year = 2012:2013)

# ITERATIVELY CALL proc_data
obj_list <- Map(proc_data, params_df$year, params_df$quarter)

# NAME ELEMENTS
nms <- paste0("YR_", params_df$year, "_Q", params_df$quarter)
obj_list <- setNames(obj_list, nm)

# OUTPUT
obj_list$YR_2012_Q1
obj_list$YR_2012_Q2
...
  •  Tags:  
  • r
  • Related