LifeLongLearner
LifeLongLearner

Reputation: 21

Comparisons of lists in R

I am trying to compare a list of a numeric variable with another list of a variable in which each variable is a list of numbers itself. What will be the best way to approach it in R?

For example:

a=10
b=20
c=30
d=40
list1 <- c(a,b,c,d)

e <- c(1,2,3,4,5)
f <- c(6,7,8,9,10)
g <- c(11,12,13,14)
h <- c(15,16,17,18)
list2 <- c(e,f,g,h)

I want to find out whether each element of list1 is greater than each element of each list of variables in list2.

Upvotes: 0

Views: 116

Answers (1)

Bruno
Bruno

Reputation: 4150

You can do a nested map

a=10
b=20
c=30
d=40
list1 <- list(a,b,c,d)

e <- c(1,2,3,4,5)
f <- c(6,7,8,9,10)
g <- c(11,12,13,14)
h <- c(15,16,17,18)
list2 <- list(e,f,g,h)

library(tidyverse)
#> Warning: package 'forcats' was built under R version 3.6.3

map(.x = list1,.f = ~map(list2,.f = function(y) .x > y))
#> [[1]]
#> [[1]][[1]]
#> [1] TRUE TRUE TRUE TRUE TRUE
#> 
#> [[1]][[2]]
#> [1]  TRUE  TRUE  TRUE  TRUE FALSE
#> 
#> [[1]][[3]]
#> [1] FALSE FALSE FALSE FALSE
#> 
#> [[1]][[4]]
#> [1] FALSE FALSE FALSE FALSE
#> 
#> 
#> [[2]]
#> [[2]][[1]]
#> [1] TRUE TRUE TRUE TRUE TRUE
#> 
#> [[2]][[2]]
#> [1] TRUE TRUE TRUE TRUE TRUE
#> 
#> [[2]][[3]]
#> [1] TRUE TRUE TRUE TRUE
#> 
#> [[2]][[4]]
#> [1] TRUE TRUE TRUE TRUE
#> 
#> 
#> [[3]]
#> [[3]][[1]]
#> [1] TRUE TRUE TRUE TRUE TRUE
#> 
#> [[3]][[2]]
#> [1] TRUE TRUE TRUE TRUE TRUE
#> 
#> [[3]][[3]]
#> [1] TRUE TRUE TRUE TRUE
#> 
#> [[3]][[4]]
#> [1] TRUE TRUE TRUE TRUE
#> 
#> 
#> [[4]]
#> [[4]][[1]]
#> [1] TRUE TRUE TRUE TRUE TRUE
#> 
#> [[4]][[2]]
#> [1] TRUE TRUE TRUE TRUE TRUE
#> 
#> [[4]][[3]]
#> [1] TRUE TRUE TRUE TRUE
#> 
#> [[4]][[4]]
#> [1] TRUE TRUE TRUE TRUE

Created on 2020-03-31 by the reprex package (v0.3.0)

Upvotes: 1

Related Questions