1

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 ?

1
  • out <- list("b" = b, "c" = c, "d" = d) should be out <- sum(b,c,d) Commented Jul 13, 2017 at 20:55

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

3 Comments

Great! Don't forget result[["b"]] + result[["c"]] + result[["d"]]
Just one more variant if you only wanted to sum a subset of the returned values: sum(unlist(evaluate(a)[c("b","c","d")])) but your with() option is my favorite.
For me, it is not important to compute only b + c + d. This was only an example. What I wanted was to use b, c, or d in other computations. So making result <- evaluate(a) and then using result$b is the answer that I needed.
1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.