CodeGuy CodeGuy - 1 year ago 140
R Question

Returning multiple objects in an R function

How can I return multiple objects in an R function? In Java, I would make a Class, maybe

which has some private variables and encapsulates, maybe,
, 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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download