0

I have written a function that produces as output 2 matrices, say A & B, and I have used list() in order to separate them in my output. Now I would like to re-write my function so that the displayed output is ONLY matrix B unless I specify it when calling the function (however, my function has still to compute both matrices.) Basically, I would like to hide matrix A from the output unless I say otherwise.

Can I do this in R?

2 Answers 2

1

Yes.

Here's an example:

myfun <- function(a, b, Bonly=TRUE) {
  # calculations
  result <- list(a, b)
  if (Bonly) return(result[2]) else return(result)
}

Basically you set a variable that has a default in the function with the notation x=DEFAULT in the set of arguments passed to the function. The variable does not need to be specified for the function to run. If the variable has the default value then return just B, otherwise return both.

> myfun(1,2)
[[1]]
[1] 2

> myfun(1,2, FALSE)
[[1]]
[1] 1

[[2]]
[1] 2
Sign up to request clarification or add additional context in comments.

Comments

1

You can set an argument with a default value saying that matrix A should hidden, unless the user specifies it should be part of the result

myFunction <- function(<your arguments>, hideA = TRUE){

  #your computations
  ...
  output <- list(A = <matrix A>, B = <matrix B>)

  #your result
  if(hideA) output <- output$B #hide A
  return(output)
}


#calling the function
myFunction(<your args>) #A will be hidden by default
myFunction(<your args>, hideA = FALSE) #the list of matrix will be returned 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.