0

My code

source("mycustomfunction.R")

mycustomfunction(10,35,3)

returns

45

My function does this:

mycustomfunction <- function (input1,input2,input3) {
  
  output1 = input1+ input2
  output2 = input3
  
  return(output1)
  return(output2)
  
}

In Matlab, for example, LHS of your function declaration lists all output variables as such

[var1 var2] = function(input1, input2)

So the calling script gets var1 and var2 back if the call is made also like this

[a b] = namefunction(1,2)

But how is this done in R?

babipsylon
  • 325
  • 2
  • 12

1 Answers1

3

You cannot return multiple times in R function. After encountering the first return it doesn't go any further.

Return lists instead.

mycustomfunction <- function (input1,input2,input3) {
  output1 = input1 + input2
  output2 = input3
  
  return(list(output1 = output1, output2 = output2))
}

result <- mycustomfunction(10,35,3)

result
#$output1
#[1] 45

#$output2
#[1] 3

You can access individual values using $ operator.

result$output1
#[1] 45

result$output2
#[1] 3
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Thx. That can work. Is it the only solution though? So max. one output per R function? Maybe without using return? – babipsylon Jun 24 '21 at 10:14
  • Max of one output per function. Period. I know of no language that supports returning more than one thing; the distinguishing factor in some languages is that you can "collect" a function's return value into multiple objects, as in python's `var1, var2 = somefunc(...)`. There is a package for R (don't recall atm) that allows `c(var, var2) <- somefunc(...)`, but I tend to find that use a little kludgy and not as clear as `ret <- somefunc(...); ret$var1; ret$var2`. – r2evans Jun 24 '21 at 10:48