Returning multiple objects in an R function [duplicate] Returning multiple objects in an R function [duplicate] r r

Returning multiple objects in an R function [duplicate]


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 <- 12bar <- 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@ageaPerson@height


Is something along these lines what you are looking for?

x1 = function(x){  mu = mean(x)  l1 = list(s1=table(x),std=sd(x))  return(list(l1,mu))}library(Ecdat)data(Fair)x1(Fair$age)