lightsnail - 1 year ago 49

R Question

List

`a`

`a<-list(3:6,6:8,3:4,8)`

`> a`

[[1]]

[1] 3 4 5 6

[[2]]

[1] 6 7 8

[[3]]

[1] 3 4

[[4]]

[1] 8

My aim is to calculate all the products of all the 2-element combinations in each object. For example, the first object in

`a`

`3 4 5 6`

`12 15 18 20 24 30`

`42 48 56`

`0`

`Map(function(x) combn(x,2,prod),a)`

`a`

`> Map(function(x) combn(x,2,prod),a)`

[[1]]

[1] 12 15 18 20 24 30

[[2]]

[1] 42 48 56

[[3]]

[1] 12

[[4]]

[1] 2 3 4 5 6 7 8 6 8 10 12 14 16 12 15 18 21 24 20 24 28 32 30 35 40 42 48 56

So how can I get all the 2-element products of all the combinations in each object and get

`0`

My expected result is as follows:

`[[1]]`

[1] 12 15 18 20 24 30

[[2]]

[1] 42 48 56

[[3]]

[1] 12

[[4]]

[1] 0

Answer Source

Use your approach and wrap `combn`

:

```
a<-list(3:6,6:8,3:4,8)
combn2 <- function(x, ...)
if(length(x) == 1L) 0 else combn(x, ...)
Map(function(x) combn2(x,2,prod),a)
#[[1]]
#[1] 12 15 18 20 24 30
#
#[[2]]
#[1] 42 48 56
#
#[[3]]
#[1] 12
#
#[[4]]
#[1] 0
```