Reputation:
Suppose I have a list of vectors. Suppose further that I would like to have a condition based on their length. That is, I would like my function return an error if the lengths of these vectors are not equal.
For example,
x <- c(1:4)
y <- c(1:5)
z <- c(1:4)
k <- list(x, y, z)
I would like to check that their lengths are equal.
stopifnot(length(k[[1]]) == length (k[[2]]) == length(k[[3]]))
How could I generalize this code and make it works for an arbitrary number of elements of the list?
Upvotes: 1
Views: 710
Reputation: 887168
We can use lengths
with unique
stopifnot(length(unique(lengths(k)))==1)
Error: length(unique(lengths(k))) == 1 is not TRUE
The lengths
will get the length
of each of the vector
in the list
as a vector
, get the unique
and check if the length
is equal to 1. If it is not i.e. stopifnot
, give an error
Upvotes: 2