Search code examples
rfunctionlapplysapplymapply

Using a function to repeat function over a collection of filenames


I would like to write a to repeat a chunk of code over a collection of file names (names of files present in my working directory) in . I would also like to save the outputs of each line as a global environment object if possible. General structure of what I am trying to do is given below. Function name is made up.

global_environment_object_1 <- anyfunction("filename and extension").
# Repeat this over a set of filenames in the working directory and save each as a separate 
# global environment object with separate names. 

A Real life example can be:

sds22 <- get_subdatasets("EVI_2017_June_2.hdf")
sds23 <- get_subdatasets("EVI_2016_June_1.hdf") 

-where object names and file names are changing and the total number of files is 48.

Thanks for the help in advance!


Solution

  • Try using :

    #Get all the filenames
    all_files <- list.files(full.names = TRUE)
    #Probably to be specific
    #all_files <- list.files(patter = "\\.hdf$", full.names = TRUE)
    #apply get_subdatasets to each one of them
    all_data <- lapply(all_files, get_subdatasets)
    #Assign name to list output
    names(all_data) <- paste0('sds', seq_along(all_data))
    #Get the data in global environment
    list2env(all_data, .GlobalEnv)