sbac
sbac

Reputation: 2081

How to use multiple result values from a function in R?

I have the following code in R:

a <- 2
evaluate <- function(x){
  b <- 2*x
  c <- 3*x
  d <- 4*x
  out <- list("b" = b, "c" = c, "d" = d)
  return(out)
}
evaluate(a)

I obtain something like

$b
[1] 4

$c
[1] 6

$d
[1] 8

How can I compute something like b + c + d ?

Upvotes: 1

Views: 101

Answers (3)

Ansharja
Ansharja

Reputation: 1133

In R you can access list members using $ operator, followed by member name so, in your code, for example:

result = evaluate(a)
result$b + result$c + result$d

Upvotes: 1

Damian
Damian

Reputation: 1433

so many options

# with
with(evaluate(a), b + c + d)
[1] 18

# unlist the unnamed output object
sum(unlist(evaluate(a)))
[1] 18

# subset a named output object
result <- evaluate(a) 
result$b + result$c + result$d
[1] 18

# subset an unnamed output object
evaluate(a)$b + evaluate(a)$c + evaluate(a)$d
[1] 18

# custom function with fancy arguments
f <- function(...) {
   args <- unlist(...)
   sum(args)
}

f(evaluate(a))
[1] 18

Also, +1 from: @Gregor (double-bracket list subsetting)

result[["b"]] + result[["c"]] + result[["d"]]
[1] 18

Upvotes: 3

zfisher
zfisher

Reputation: 61

Your function returns a list. You could return a vector and then use the sum() function to compute the sum of the elements in the vector. If you must use a list, the 'Reduce()` function can work.

l <- list(2, 3, 4)
v <- c(2,3,4)
sum(v) # returns 9
Reduce("+", l) # returns 9

Upvotes: 0

Related Questions