Reputation: 1408
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)
Upvotes: 12
Views: 5432
Reputation: 26218
Use purrr::discard
or purrr::keep
List_data <- list("Green", "Yellow", c(NA,NA,NA), TRUE, 51.2)
purrr::discard(List_data, ~ all(is.na(.x)))
#> [[1]]
#> [1] "Green"
#>
#> [[2]]
#> [1] "Yellow"
#>
#> [[3]]
#> [1] TRUE
#>
#> [[4]]
#> [1] 51.2
Created on 2024-07-16 with reprex v2.1.1
Upvotes: 1
Reputation: 160417
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.
Upvotes: 18
Reputation: 133458
EDIT2: As per akrun's comment following may also help here.
List_data[vapply(List_data, function(x) any(!is.na(x)), logical(1))]
EDIT: As per Onyambu's comment following may help in order to remove complete element which has NA in it, thanks to Onyambu for guiding here.
List_data[!sapply(List_data, function(x) all(is.na(x)))]
Could you please try following:
lapply(List_data, function(x) x[!is.na(x)])
Upvotes: 6
Reputation: 79208
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)]
Upvotes: 7
Reputation: 20463
For a purrr
approach:
library(purrr)
List_data %>%
map(discard, is.na) %>%
compact()
Noting you can remove compact()
and get "either" solution.
Upvotes: 9