I have three lists with 2 elements each. How do I check whether every element has the same length in every list? Preferably using purrr. Thank you!
list.a = list(a = 1, b = c(1, 2))
list.b = list(a = 2, b = c(1, 2))
list.c = list(a = 3, b = c(1, 2, 3))
Should return T, T, F.
CodePudding user response:
Not entirely sure on the requirement but here's 2 potentially usefully snippets.
map_lgl(transpose(list(list.a, list.b, list.c)), ~ var(lengths(.x))==0)
a b
TRUE FALSE
or for a more general output you can manipulate easier
map_dfr(list(list.a, list.b, list.c), ~map(.x, length))
a b
1 1 2
2 1 2
3 1 3
CodePudding user response:
For any two lists:
all(lengths(list.a)==lengths(list.b))
To check if all lists are equal:
same_length <- function (x, y) all(lengths(x) == lengths(y))
Reduce(f, list(list.a, list.b, list.c))
If you want to use purrr:
same_length <- function (x, y) all(lengths(x) == lengths(y))
purrr::reduce(list(list.a, list.b, list.c), f)
CodePudding user response:
each element has the same length in every list? - This would be a single TRUE or FALSE. Based on your expected output and task I think you want to compare for specific length of list elements.
master_list <- list(list.a, list.b, list.c)
map_lgl(master_list, ~ all(lengths(.x) == 1:2))
[1] TRUE TRUE FALSE
