List comprehension in R: map, not filter

筅森魡賤 提交于 2019-12-11 04:07:30

问题


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


来源:https://stackoverflow.com/questions/26163757/list-comprehension-in-r-map-not-filter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!