Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the idiomatic way in R to return a vector of function values when the function takes no input?

Tags:

r

Suppose I write a function that takes no input but returns random variable e.g.,

example.f <- function() runif(1, 0, 1)

If I want to get a vector of length 100 of results returned from this function, I can't do this:

rep(example.f(), 100)

as it just repeats the first returned value. I could do it like this, with an anonymous function:

sapply(1:100, function(x) example.f())

but this strikes me as a bit inelegant. Is there another way?

like image 316
John Horton Avatar asked Feb 22 '23 12:02

John Horton


1 Answers

Use replicate:

replicate(100, example.f())
like image 100
David Robinson Avatar answered Feb 24 '23 13:02

David Robinson