1

In MATLAB, it's possible for a function to return more than one output, as in the following example:

[x y] = size(someMatrix);

Is something like this possible in R? All functions seem to return, at most, one argument. For example, it would be great to declare the number of rows and columns of a data frame with a single command, as in the following code:

[x y] <- dim(some.data.frame)

I've looked, but I can't find an answer to this question.

Gyan Veda
  • 6,309
  • 11
  • 41
  • 66

1 Answers1

4

The R paradigm is to group together what belongs together.

That's why dim(obj) returns a vector of two values and not two individual variables. Coming from another programming language background, this may seem counterintuitive at first. But it makes for readable code and is expected by many R functions and packages.

You can use list() to group together multiple objects (of any type) and return that list from within a function:

multiple_returns <- function() {
  a <- "char"
  b <- 1
  c <- matrix(c(1,2,3,4), ncol=2)
  return(list(a, b, c))
}

returned <- multiple_returns()
returned[[1]]
returned[[2]]
returned[[3]]
coanil
  • 272
  • 1
  • 7