简体   繁体   中英

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!!

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

You may store workingdf in an attr ibute.

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

Calculation with the result as usual.

r <- mu_fuc(d, Var1)
r - 5
# [1] -1
# attr(,"workingdf")
#   ID Var1
# 2  6    1

To avoid the attribute to be displayed for cosmetic reasons use as.numeric

as.numeric(r) - 5
# [1] -1

or

r2 <- as.numeric(mu_fuc(d, Var1))
r2 - 5
# [1] -1

To get workingdf , fetch it from the attribute.

wdf <- attr(mu_fuc(d, Var1), "workingdf")
wdf
#   ID Var1
# 2  6    1

Data:

d <- data.frame(ID=5:6, Var1=c(3, 1))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM