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

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"
    
asked by anonymous 30.10.2018 / 19:40

1 answer

4

If you want to return more than one object, you should use 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
    
30.10.2018 / 20:15