Generate vector of values from closure

This type of thing is easy in F# but I can't figure out how to do it in R. I want to generate a vector with values generated from a closure. In F# it works something like this. The first argument is the number of elements you would want, the second is the iterator for the closure and the last argument is the closure to generate the values. Is something like this possible in R? I use it all the time in F#.

result <- GenerateVector(5, n, function(n){
    n*10
})

Would result in:

result =
10
20
30
40
50

Answers


Further to my comment, if the second argument is not needed (i.e. you don't need to specify what the iterator is), then we could write GenerateVector() like this:

GenerateVector <- function(x, FUN) {
    do.call(FUN, list(seq_len(x)))
}

R> GenerateVector(5, FUN = function(n) {n*10})
[1] 10 20 30 40 50

Whether that will work for you more generally will depend on whether FUN is a vectorised function (like your example) or not. Of course, you will hit major inefficiencies if you use functions that don't accept vectors, so this is probably not too great an issue.

In general, these things are far easier to write using normal R conventions:

R> 1:5 * 10
[1] 10 20 30 40 50
R> foo <- function(n) n * 10
R> foo(1:5)
[1] 10 20 30 40 50

All do.call() in my example is doing is writing the last two lines of R code above for you.


Need Your Help

Can one's post request data be sniffed?

security post

I apologize, I am new to this and assume that I will mix some terms up.

Python Celery Chain of Tasks on a Single Node

python celery

I have two celery nodes on 2 machines (n1, n2) and my task enqueue is on another machine (main).

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.