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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With