Reputation: 1543
I am looking for some clean way to implement this operation. Say, I have a list as following:
gate_entry <- list(gate1 = "Andy",
gate2 = "Bob",
gate3 = "Chad",
gate4 = NA,
gate5 = " Dan",
gate6 = NA,
gate7 = NULL)
NA
and NULL
occurrences are possible and beyond my code's control.
Somewhere else in my codes, I register a list of the same length as gate_entry
as following:
amount_carry <- list(10, 20, 15, NULL, NA, NA, NA)
For each element in gate_entry
that is a non-empty string , I want to check if the corresponding element in amount_carry
is numeric. If there is at least one occurrence where this condition is not true, return FALSE
. Just like the elements in gate_entry
, the elements in amount_carry
could be NA
or NULL
.
In this case, I expect element 1, 2, 3 and 5 in amount_carry
to be numeric (and return TRUE
). But since element 5 is NA
, this operation should return FALSE
.
Upvotes: 0
Views: 50
Reputation: 206606
First, create a helper function to test for non-null, non-missing values
is_present <- function(x) !is.null(x) && !is.na(x)
We can test all the gate_entry
and amount_carry
values with
gate_ok <- sapply(gate_entry, is_present)
amount_ok <- sapply(amount_carry, is_present)
Now the only values that aren't allowed are when gate_ok
is true but amount_ok
is not so we just need to make sure there aren't any of those.
!any(gate_ok & !amount_ok)
# [1] FALSE
Upvotes: 3