Home > Back-end >  Performing operations between two lists of vectors in R
Performing operations between two lists of vectors in R

Time:12-22

I have two large lists with 1000 elements each, for example:

list.A
$ V1    : num [1:141089] 1 2 3 4 5 ...
$ V2    : num [1:141089] 2 1 4 3 6 ...
$ ..
$ V1000 : num [1:141089] 5 6 7 8 9 ...


list.B
$ V1    : num [1:141089] 5 4 3 2 1 ...
$ V2    : num [1:141089] 4 5 2 3 0 ...
$ ..
$ V1000 : num [1:141089] 9 8 7 6 5 ...

see list.A example figure

I would like to perform operations for nth vector in one list by all vector in the second list. For instance: V1 in list.A against V1 in list.B, V2 in list.B, until V1000 in list.B. And the same for V2 until V1000 in list.A.

So far, here is how my code looks like.

list.diff <- Map(function(num1, num2) sum(abs(num1 - num2)/20)/(141089), list.A, list.B)

By using Map in R, I can only perform operations for nth vector in one list by the nth vector in the second list. For instance, V1 in list.A against V1 in list.B, and then V2 in list.A against V2 in list.B.

Any suggestions how to solve this? I am new to R and stackoverflow. Many thanks for taking the time to answer.

CodePudding user response:

You could use nested lapply() and sapply() calls:

set.seed(13)

list.A <- setNames(
  replicate(3, sample(0:9, 3, replace = TRUE), simplify = FALSE),
  paste0("V", 1:3)
)

list.B <- setNames(
  replicate(3, sample(0:9, 3, replace = TRUE), simplify = FALSE),
  paste0("V", 1:3)
)

list.diff <- lapply(
  list.A, 
  \(num1) sapply(list.B, \(num2) mean(abs(num1 - num2)/20))
)

list.diff
$V1
       V1        V2        V3 
0.2666667 0.1166667 0.1833333 

$V2
       V1        V2        V3 
0.2333333 0.1500000 0.1833333 

$V3
        V1         V2         V3 
0.15000000 0.13333333 0.06666667 

Note, I also simplified sum(...)/141089 to mean(...).

  • Related