Reputation: 4305
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
Upvotes: 1
Views: 259
Reputation: 174813
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.
Upvotes: 3
Reputation: 179428
Possibly something like sapply
might do it:
sapply(1:5, function(n)10*n)
[1] 10 20 30 40 50
The similarity is that sapply
takes a list as input, applies a function to each element in that list, and returns the result in a list. Since a list is itself a vector, you can do the same with an input vector.
In this example we use the :
operator to construct a vector sequence.
Upvotes: 1