Search code examples
rfunctiontypesreferenceassign

Store an object for later use when writing a function


I am writing a function that helps me subset a dataframe, and then feeds the dataframe to another action. The output for this function would be the result for the second action. However, since I would still need the cleaned dataframe for another purpose, I was wondering if I can store such dataframe in the environment so that it can be called for later?

For instance, Let's say I have this dataframe.

      ID   Var1
   1   5     3
   2   6     1

And my function is like this:

mu_fuc <- function(df, condition) {

#clean dataset
  condition <- eval(as.list(match.call())$condition, df)
  workingdf <- subset(df, condition < 3). ####I am trying to store this working dataframe for later use. 

#second action 
  result = sum(workingdf[condition]) 

#output of the function
  return(result) 
}

Since the result of the function would be used later as well, I can't add workingdf to return. Otherwise, the output of the function would contain workingdf when I try to feed the output to another function, which is something I don't want.

So for example, in this case, if I want to do, I need the output of the function to be of integers only.

my_fun(data, Var1) - 5

I hope I am making myself clear.

Any help is greatly appreciated!!


Solution

  • You can return a list from the function with the result that you want.

    mu_fuc <- function(df, condition) {
      #clean dataset
      condition <- eval(as.list(match.call())$condition, df)
      workingdf <- subset(df, condition < 3)
      
      #second action 
      result = sum(workingdf) 
      
      #output of the function
      return(list(result = result, workingdf = workingdf)) 
    }
    

    Call it as :

    output <- mu_fuc(df, Var1)
    

    You can separate out the result using $ operator and process them separately.

    output$result
    output$workingdf