Returning multiple objects in an R function

831    Asked by JulianSpringer in Data Science , Asked on Jul 14, 2021

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 a list of characters and an integer?

Answered by Kumar Menon

In R programming, functions do not return multiple values, however, you can create a list that contains multiple objects that you want a function to return.

For R to return multiple values, use the below code:

For example:

x <- c(3,4,7,9,34,24,5,7,8)
fun = function(x){
  mn = mean(x)
  lt = list(f1=table(x),std=sd(x))
  newlist <- list(lt,mn)
  return(newlist)
}
fun(x)
Output:
[[1]]
[[1]]$f1
x
 3 4 5 7 8 9 24 34
 1 1 1 2 1 1 1 1
[[1]]$std
[1] 10.55673
[[2]]
[1] 11.22222

Your Answer

Interviews

Parent Categories