What is the idiomatic way in R to return a vector of function values ​​when the function does not accept an input?

Suppose I write a function that does not accept input but returns a random variable, for example,

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

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

 rep(example.f(), 100) 

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

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

but it seems to me a little inelegant. Is there another way?

+4
source share
1 answer

Use replication:

 replicate(100, example.f()) 
+8
source

Source: https://habr.com/ru/post/1396107/


All Articles