用R重写此列表理解 [英] Rewrite this list-comprehension in R

查看:57
本文介绍了用R重写此列表理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

>>> [(x*y) for (x,y) in zip(range(3), (1,11,111))]
[0, 11, 222]                                             

不是这样

> data.frame(0:2,c(1,11,111))
  X0.2 c.1..11..111.
1    0             1
2    1            11
3    2           111
> data.frame(0:2,c(1,11,111))->a
> a[1]*a[2]
  X0.2
1    0
2   11
3  222

但类似这样的东西

lapply(a, function(x)
{   ...how can I access here the parameters of x? 
    (not using x[1] or x[2])
}

推荐答案

对于一般模式,也许

Map(`*`, 0:2, c(1, 11, 111))

unlist(Map(`*`, 0:2, c(1, 11, 111)))

或更明确地

Map(function(x, y) x*y, 0:2, c(1, 11, 111))

(我喜欢Map优于Steve的mapply,因为它默认情况下不进行简化,键入较短,并且可以与手册页中记录的其他功能配合使用,例如ReduceNegate).

(I like Map better than Steve's mapply because it does not simplify by default, is shorter to type, and plays well with the other functional functions documented on its man page, e.g., Reduce, Filter, and Negate).

该特定问题的较早答案(已删除)仅为0:2 * c(1, 11, 111),这将更加有效.

An earlier answer for the particular question, since removed, was just 0:2 * c(1, 11, 111), which would be much more efficient.

这篇关于用R重写此列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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