Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the products of all the combinations in R

List a is as follows:

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 is 3 4 5 6, so all the products of the first object is 12 15 18 20 24 30, and all the products of the second object is 42 48 56. BUT when there is only one element in the object, the output should be 0. I planed to solve the problem by using Map(function(x) combn(x,2,prod),a), but it was not suitable when there was only one element in the object (such as the 4th object in 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 when there is only one element at the same time? Thanks!

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 
like image 750
lightsnail Avatar asked Aug 22 '16 16:08

lightsnail


Video Answer


2 Answers

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
like image 191
Roland Avatar answered Sep 30 '22 00:09

Roland


We can try with an if/else condition

Map(function(x) if(length(x)==1) 0 else combn(x,2, FUN = prod),a)
#[[1]]
#[1] 12 15 18 20 24 30

#[[2]]
#[1] 42 48 56

#[[3]]
#[1] 12

#[[4]]
#[1] 0

I think @Roland answered it first (9 secs before me, though I didn't see his answer), so a variation of the above is

ifelse(lengths(a)==1, 0, Map(function(x) combn(x, 2, prod), a))

Or with lapply

ifelse(lengths(a)==1, 0, lapply(a, function(x) combn(x, 2, FUN = prod)))
like image 39
akrun Avatar answered Sep 30 '22 01:09

akrun