Search code examples
rfunctionplotglobalstore

Strategies for using functions to store within the global env


Let's say we have the following data frame:

# Data
Id <- c(1,2,3,4,5,6,7,8,9,10)
Type <- c("Beginner", "Expert", "Intermediate", "Beginner", 
  "Professional", "Expert", "Intermediate", "Professional", 
  "Professional", "Expert")
Response<- c(1,1,2,2,1,2,1,2,1,1)
Successful <- data.frame(Id, Type, Response)
Successful

# Dataframe
#   Successful
Id  Type             Response    
1   Beginner         1
2   Expert           1
3   Intermediate     2
4   Beginner         2
5   Professional     1
6   Expert           2
7   Intermediate     1
8   Professional     2
9   Professional     1
10  Expert           1

I know that I could store it as an object (DFRespType) in the global environment by doing the following:

 DFRespType <- 
  as.data.frame(round(100*prop.table(table(Successful$Response, 
                                   Successful$Type),2), 1))

But instead, I would like to create a function for storing the object to make doing this a lot more efficient. Below I tried to make the StoreDF function:

StoreDF <- function(DFName, dataset, variable1, variable2){
  DFName <- as.data.frame(round(100*prop.table(table(dataset$variable1, 
                                              dataset$variable2),2), 1))
}

But when I try and use it in the following way, nothing is stored:

StoreDF(DFRespType, Successful, Response, Type)

Any help with this would be gratefully appreciated.


Solution

  • Don't store objects in global environment from inside the function. Instead return the dataframe back from the function. Also using quoted variables to subset the dataframe.

    StoreDF <- function(dataset, variable1, variable2){
        as.data.frame(round(100* prop.table(table(dataset[[variable1]], 
                            dataset[[variable2]]),2), 1))
    }
    
    DFRespType <- StoreDF(Successful, "Response", "Type")
    DFRespType
    
    #  Var1         Var2 Freq
    #1    1     Beginner 50.0
    #2    2     Beginner 50.0
    #3    1       Expert 66.7
    #4    2       Expert 33.3
    #5    1 Intermediate 50.0
    #6    2 Intermediate 50.0
    #7    1 Professional 66.7
    #8    2 Professional 33.3