# [R] apply on function with vector as result

Sarah Goslee sarah.goslee at gmail.com
Fri Dec 9 12:54:54 CET 2011

```This would be a whole lot easier if we had a reproducible example,
or at least knew what your output data actually looked like, and an
example of what you *wanted* it to look like.

> c(c(1,2), c(3,4))
 1 2 3 4

c(c(), c()) is a single vector already.

But when I try an approximation of your non-reproduclble example, that's
not what I get anyway. I get the expected matrix:

> myfunc <- function(x) {a=x; b=x-1; c(a, b) }
> ys <- sapply(1:5, myfunc)
> ys
[,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5
[2,]    0    1    2    3    4

And from there, it's not at all clear what you mean by "one vector" -
in what order? All of the a then all of the b values? abab?

as.vector(ys) and as.vector(t(ys)) will accomplish those.

Or do you mean simply
as <- ys[1,]
bs <- ys[2,]

But all this is academic since I don't know what your data look like, really.

Sarah

On Fri, Dec 9, 2011 at 6:40 AM, Christof Kluß <ckluss at email.uni-kiel.de> wrote:
> Hi,
>
> a have some code like
>
> myfunc <- function(x) { ...;  return c(a,b) }
>
> ys <- sapply(0:100,myfunc)
>
> so I get something like c(c(a1,b1),c(a2,b2),...)
>
> But now I need the "as" and "bs" in one vector
>
> as <- apply(ys, function(c(a,b)) a)
> bs <- apply(ys, function(c(a,b)) b)
>
> Can you help me with the correct syntax, instead of my pseudo code?
>
> thx
> Christof
>

--
Sarah Goslee
http://www.functionaldiversity.org

```