简体   繁体   中英

Return function not accessible in R

I have made a function and then returning an object named final, However when I try to access the object outside of the function it give me error object not found.

I am not sure where I am getting wrong this seems to be fairly simple and correct, when I try to exclucde the function and just run the statements, I am able to access the final object only when trying to return the object I am not able to do so.

I am not sure why this is happening.


myfunction <- function(lo,X_train,y_train,X_test,y_test,pred){
  
  
  
  loan_number<-as.numeric(testing$lo)
  
  xgb.train = xgb.DMatrix(data=X_train,label=y_train)
  xgb.test = xgb.DMatrix(data=X_test,label=y_test)

  explainer = buildExplainer(xgb,xgb.train, type="binary", base_score = 0.5, trees = NULL)
  pred.breakdown = explainPredictions(xgb, explainer, X_test)
  pred.breakdown<-as.data.frame(pred.breakdown)
  
  pred.breakdown <- pred.breakdown %>% do(.[!duplicated(names(.))])

  pred_break<-pred.breakdown %>%
    #Create an id by row
    dplyr::mutate(id=1:n()) %>%
    #Reshape
    pivot_longer(cols = -id) %>%
    #Arrange
    arrange(id,-value) %>%
    #Filter top 5
    group_by(id) %>%
    dplyr::mutate(Var=1:n()) %>%
    filter(Var<=5) %>%
    select(-c(value,Var)) %>%
    #Format
    dplyr::mutate(Var=paste0('Attribute',1:n())) %>%
    pivot_wider(names_from = Var,values_from=name) %>%
    ungroup() %>%
    select(-id)
  
  pred_break<-as.data.frame(pred_break)
  prop_score<-pred
  
  final<-as.data.frame(cbind(loan_number,prop_score,pred_break))
  print("final exec")
  return(final)
}
myfunction(loan_number,X_train,y_train,X_test,y_test,pred)
final<-as.data.frame(final)

Printing final exec to check if everything is working or not , Apparently it's weird that I am not able to access the final object which is passed to return statement.

R is primarily a functional programming language with lexical scoping. This line:

myfunction(loan_number,X_train,y_train,X_test,y_test,pred)

runs your function and returns the VALUE of final , but it's returning to the console. The function's return needs to be assigned to another variable in order to be used, like @Duck suggests:

final <- myfunction(loan_number,X_train,y_train,X_test,y_test,pred)

This is different than final in your function. That final is inaccessible outside of the function.

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