Rewrite this list comprehension in R

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

Not like that

 > 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]) } 
+4
source share
3 answers

For the big picture, maybe

 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 mapply because it’s not simplified by default, it’s shorter for input and works well with other functionalities documented on its manual page, such as Reduce , Filter and Negate ).

The earlier answer to a specific question, since deleted, was just 0:2 * c(1, 11, 111) , which would be much more efficient.

+15
source

There is an answer to Josh, but if you need a generalization of what zip does for you in the Python context, look at mapply , which applies to several “things” at once and applies a function to the i th element from each “thing”, for example:

 x1 <- 0:2 x2 <- c(1, 11, 111) mapply(function(x, y) x*y, x1, x2) ## [1] 0 11 222 

and

 x3 <- c(10, 20, 30) mapply(function(x, y, z) x * y + z, x1, x2, x3) ## [1] 10 31 252 

Update: see also Martin's answer: it says well that you want mapply , you can really use the Map convenience instead.

+6
source

I don’t understand your question. lapply moves through the list items. This way, your anonymous function will be applied to each column a , but your example seems to indicate that you want to apply a binary function to two columns.

I assume you want something like:

 do.call("*",a) # [1] 0 11 222 
+1
source

Source: https://habr.com/ru/post/1389506/


All Articles