I have a function that uses runif
to calculate some value, so each time it is called, the result varies slightly. I want to calculate the mean of the result of several calls to the function.
For this, it would be great to create a vector with the results of repeated function calls
Is there a simple idiomatic way to create a vector of repeated function calls? I tries
rep(my_function_call(), 10)
but it simply calls the function once and repeats the result 10 times. I want the function evaluated 10 times, and a vector of the results.
1.1. How to repeat vectors in R. You can use the rep() function in several ways if you want to repeat the complete vector.
function() in R, allows you to convert a non-vector object into a vector. For example, if you have a matrix as an object and you wanted to convert it into a vector, then you can use the as. vector() function to get this done. See an example below for a better understanding of as.
Repeat loop in R is used to iterate over a block of code multiple number of times. And also it executes the same code again and again until a break statement is found.
The is. vector() function takes an object as an input and returns TRUE if the input object is a vector. It returns FALSE if the object is not a vector.
replicate
is your friend. See ?replicate
replicate(10, my_function_call()) # this would be what you're looking for
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With