I want to remove all elements in this list that contain only NA:
List_data <- list("Green", "Yellow", c(NA,NA,NA), TRUE, 51.2)
If you mean remove the entire element (and not leave the empty name behind), try:
Filter(function(a) any(!is.na(a)), List_data)
Edit: using Onyambu's suggestion (thanks!) of Negate(anyNA)
, this would be
Filter(Negate(anyNA), List_data)
though admittedly this changes the logic from "something not-NA exists" (first code) to "no NA exists" (second code), definitely a logical change.
You can also do:
List_data[!sapply(List_data, function(x) all(is.na(x)))]
or as @snoram pointed out:
List_data[sapply(List_data, Negate(anyNA))]
which can also be expressed as:
List_data[!sapply(List_data, anyNA)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With