Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning multiple objects in an R function [duplicate]

Tags:

function

r

How can I return multiple objects in an R function? In Java, I would make a Class, maybe Person which has some private variables and encapsulates, maybe, height, age, etc.

But in R, I need to pass around groups of data. For example, how can I make an R function return both an list of characters and an integer?

like image 355
CodeGuy Avatar asked Oct 16 '22 14:10

CodeGuy


People also ask

Can an R function return multiple objects?

The return() function can return only a single object. If we want to return multiple values in R, we can use a list (or other objects) and return it.

How do I return multiple plots in R?

In R (as in most other languages, actually), once you get to return , everything else won't be executed. So, if you want to return multiple things, you can always put results into a list and return that instead. So you'll have something like return(list(plotA = plotA, plotB = plotB)) or similar.

Can we return 2 variables?

You cannot explicitly return two variables from a single function, but there are various ways you could concatenate the two variables in order to return them.


2 Answers

Unlike many other languages, R functions don't return multiple objects in the strict sense. The most general way to handle this is to return a list object. So if you have an integer foo and a vector of strings bar in your function, you could create a list that combines these items:

foo <- 12
bar <- c("a", "b", "e")
newList <- list("integer" = foo, "names" = bar)

Then return this list.

After calling your function, you can then access each of these with newList$integer or newList$names.

Other object types might work better for various purposes, but the list object is a good way to get started.

like image 269
ChadBDot Avatar answered Oct 19 '22 04:10

ChadBDot


Similarly in Java, you can create a S4 class in R that encapsulates your information:

setClass(Class="Person",
         representation(
            height="numeric",
            age="numeric"
          )
)

Then your function can return an instance of this class:

myFunction = function(age=28, height=176){
  return(new("Person",
          age=age,
          height=height))
}

and you can access your information:

aPerson = myFunction()

aPerson@age
aPerson@height
like image 36
RockScience Avatar answered Oct 19 '22 02:10

RockScience