So, this question tells how to perform a list comprehension in R to filter out new values.
I'm wondering, what is the standard R way of writing a list comprehension which is generating new values?
Basically, if we have a function f
and vector x
, I want the list f(el) for el in x
. (This is like map in functional programming).
In Python, this would just be [f(el) for el in x]
. How do I write this in R, in the standard way?
The problem is, right now I have for-loops:
result = c(0)
for (i in 1:length(x))
{
result[i] = f(x[i])
}
Is there a more R-like way to write this code, to avoid the overhead of for-loops?
I would recommend taking a look at the R package rlist which provides a number of utility functions that make it very easy to work with lists. For example, you could write
Following works without any special functions:
If x is a vector, result of f(x) will be a vector.