R中的列表理解:地图,而不是过滤器 [英] List comprehension in R: map, not filter

查看:72
本文介绍了R中的列表理解:地图,而不是过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,此问题讲述了如何在R中执行列表理解以过滤出新的值.

So, this question tells how to perform a list comprehension in R to filter out new values.

我想知道,编写生成新值的列表理解的标准R方法是什么?

I'm wondering, what is the standard R way of writing a list comprehension which is generating new values?

基本上,如果我们有函数f和向量x,则需要列表f(el) for el in x. (这就像函数编程中的map一样.)

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).

在Python中,它就是[f(el) for el in x].如何以标准方式在R中编写代码?

In Python, this would just be [f(el) for el in x]. How do I write this in R, in the standard way?

问题是,现在我有for循环:

The problem is, right now I have for-loops:

result = c(0)
for (i in 1:length(x))
{
    result[i] = f(x[i])
}

是否有更类似于R的方式编写此代码,以避免for循环的开销?

Is there a more R-like way to write this code, to avoid the overhead of for-loops?

推荐答案

我建议您看一下R包 rlist 提供了许多实用程序功能,这些功能使使用列表变得非常容易.例如,您可以写

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))

这篇关于R中的列表理解:地图,而不是过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆