Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove an element from a list that contains only NA?

Tags:

r

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)
like image 561
bic ton Avatar asked Jul 30 '18 16:07

bic ton


2 Answers

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.

like image 199
r2evans Avatar answered Nov 09 '22 16:11

r2evans


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)]
like image 40
KU99 Avatar answered Nov 09 '22 15:11

KU99