Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating vector of results of repeated function calls in R

Tags:

r

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.

like image 775
Julian Avatar asked Nov 09 '12 17:11

Julian


People also ask

Which of the following functions is used to create a vector with repeated values in R?

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.

How do I create a vector function in R?

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.

Which command is used to repeat same value in R?

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.

Which of the following function is used to return a vector in R?

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.


1 Answers

replicate is your friend. See ?replicate

replicate(10, my_function_call()) # this would be what you're looking for 
like image 119
Jilber Urbina Avatar answered Sep 18 '22 15:09

Jilber Urbina