user2374133
user2374133

Reputation: 193

R: how do you apply a function to a vector and get a vector of different length?

I have a list of means, for example

avgs = c(1,2,3)

and a function:

simulate <- function (avg)
{ rnorm(n=10,m=avg,sd=1) }

What is the best way to get a vector of 30 values, rather than a multidimensional array from sapply(avgs,simulate)?

Upvotes: 1

Views: 41

Answers (1)

Peyton
Peyton

Reputation: 7396

In your case, just take advantage of the fact that rnorm is vectorized and thus will accept entire vectors as arguments:

rnorm(30, avgs, 1)

You can also remove dimensions from your matrix with c:

c(sapply(avgs, simulate))

but this approach is slower and less direct.

Upvotes: 2

Related Questions