Stirling
Stirling

Reputation: 391

Apply multiple-output function to vector in R

I have a function that returns multiple outputs as a list. I want to apply this function to a vector of inputs, and collect the result into a list of vectors. The code below does what I want, but has a couple of drawbacks. First, I need to explicitly give the names "square" and "cube" of the output list of f. Second, I need to evaluate the function f twice for each value of x. Is there a way to get the same output as the code below while avoiding the drawbacks?

f <- function(x) list(square = x^2, cube = x^3)
x <- c(1, 2, 3)
desired.output <- list(
  square = sapply(X = x, FUN = function(x) f(x)$square),
  cube = sapply(X = x, FUN = function(x) f(x)$cube)
)

Upvotes: 1

Views: 448

Answers (3)

Rushabh Patel
Rushabh Patel

Reputation: 2764

You can try -

> mapply(f, x)

    [,1] [,2] [,3]
square 1    4    9   
cube   1    8    27  

OR

> Map(f,x)

[[1]]
[[1]]$square
[1] 1

[[1]]$cube
[1] 1


[[2]]
[[2]]$square
[1] 4

[[2]]$cube
[1] 8


[[3]]
[[3]]$square
[1] 9

[[3]]$cube
[1] 27

Upvotes: 1

akrun
akrun

Reputation: 886938

This should be simply applying the function over x

f(x)
#$square
#[1] 1 4 9

#$cube
#[1]  1  8 27

Upvotes: 3

MrNetherlands
MrNetherlands

Reputation: 940

You can try the function do.call for this

do.call(f, list(x))

Upvotes: 2

Related Questions