1

I am trying to create a function in R that imports data. I would like to save each dataset with a different object name and save it to the global environment. The four arguments I am passing to the function are 1.) Month, 2.) ID, 3.) root , and 4.) file. Both root and file specify the filepath. The code is below:

# Import Data 
ImportData <- function(Month, ID, root, file){

  Month_Data_ID_1 <<- read_sas(paste(root,file, sep = ""))
  return(Month_Data_ID_1)
}
# Function
ImportData(Jan, A7 , Base,"select_jan_on.sas7bdat")
ImportData(Feb, A8 , Base,"select_feb_on.sas7bdat")

If I run this function multiple times, the object name does not change to the new arguments that are passed through. Instead a global dataset called 'Month_Data_ID_1' is saved. How can I fix this. I also read that this is bad practice? Is there a better way to import and dynamically rename objects?

Thanks!

ldan
  • 41
  • 1
  • 6
  • This really isn't a very R-like way to do things. Functions should really return data rather than assign variables to the global environment. Tehcnically you can do this with things like `assign()` but this just leads to other problems later when you try to access all your objects. It would be better to store related data in a list like: https://stackoverflow.com/a/24376207/2372064 – MrFlick Feb 12 '20 at 00:08
  • @MrFlick is right that a list would be better. If you want to use your function though, add the `assign` function to your function. For the object name argument in the assign function, you can `paste` your arguments together to make the file name adapt each time you change the arguments in your function. Set the value argument equal to the dataframe that is created in the first line of your function, and set environment to .GlobalEnv. – Tanner33 Feb 12 '20 at 05:47

0 Answers0