Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rewrite this list-comprehension in R

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

Not like this

> 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

but something like this

lapply(a, function(x)
{   ...how can I access here the parameters of x? 
    (not using x[1] or x[2])
}
like image 812
hhh Avatar asked Nov 29 '22 03:11

hhh


1 Answers

For the general pattern, perhaps

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

or

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

or more explicitly

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

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

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

like image 137
Martin Morgan Avatar answered Dec 04 '22 02:12

Martin Morgan