How do you return multiple objects in a function of r?

Asked

Viewed 404 times

2

The basic structure of a function in R is:

function( arglist ) expr
return(value)

My question is how to return multiple information. For example:

funcao<-function(a,b,c){
 if(c==1){d<-a+b}
 else{d<-a-b}
return(d)
}

I want to know how I can add more information in Return.
So would have:

exemplo<-funcao(1,2,1)
>exemplo
3
>exemplo$metodo
"soma"

1 answer

4


If you want to return more than one object, you must use one list():

         f <- function(a, b, c) {
  d <- a + (b * c)
  return(list(a = a, b = b, c = c, d = d))
}


f(2, 4, 6)
# $a
# [1] 2
# 
# $b
# [1] 4
# 
# $c
# [1] 6
# 
# $d
# [1] 26

f(2, 4, 6)$d
# [1] 26

Browser other questions tagged

You are not signed in. Login or sign up in order to post.