List comprehension in R: map, not filter

2019-07-11 05:20发布

问题:

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 fand 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?

回答1:

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

list.map(x, x ~ x + f(x))


回答2:

Following works without any special functions:

> x <- 1:10
> f <- function(x) {x+log(x)}
> 
> f(x)
 [1]  1.000000  2.693147  4.098612  5.386294  6.609438  7.791759  8.945910 10.079442 11.197225 12.302585

> result = f(x)
> result
 [1]  1.000000  2.693147  4.098612  5.386294  6.609438  7.791759  8.945910 10.079442 11.197225 12.302585

If x is a vector, result of f(x) will be a vector.

> y = 12
> f(y)
[1] 14.48491