|
9 | 9 | #' compact_list(c(1, NA, NA), remove_na = TRUE) |
10 | 10 | #' @export |
11 | 11 | compact_list <- function(x, remove_na = FALSE) { |
12 | | - if (remove_na) { |
13 | | - x[ |
14 | | - !sapply(x, function(i) { |
15 | | - !is_model(i) && |
16 | | - !inherits(i, c("Formula", "gFormula")) && |
17 | | - !is.function(i) && |
18 | | - (all(is.na(i)) || any(.safe(as.character(i) == "NULL", FALSE), na.rm = TRUE)) |
19 | | - }) |
20 | | - ] |
21 | | - } else { |
22 | | - x[ |
23 | | - !sapply(x, function(i) { |
24 | | - !is_model(i) && |
25 | | - !inherits(i, c("Formula", "gFormula")) && |
26 | | - !is.function(i) && |
27 | | - (length(i) == 0L || |
28 | | - is.null(i) || |
29 | | - any(.safe(as.character(i) == "NULL", FALSE), na.rm = TRUE)) |
30 | | - }) |
31 | | - ] |
| 12 | + .is_null_string <- function(object) { |
| 13 | + if (is.character(object) || is.factor(object)) { |
| 14 | + return(any(object == "NULL", na.rm = TRUE)) |
| 15 | + } |
| 16 | + if (is.atomic(object)) { |
| 17 | + return(FALSE) |
| 18 | + } |
| 19 | + if (is.list(object)) { |
| 20 | + return(any(rapply(object, is_null_string, how = "unlist"))) |
| 21 | + } |
| 22 | + # recursion on nested lists |
| 23 | + .safe(any(as.character(object) == "NULL", na.rm = TRUE), FALSE) |
32 | 24 | } |
| 25 | + |
| 26 | + is_remove <- vapply( |
| 27 | + x, |
| 28 | + function(i) { |
| 29 | + if (is_model(i) || inherits(i, c("Formula", "gFormula")) || is.function(i)) { |
| 30 | + return(FALSE) |
| 31 | + } |
| 32 | + if (remove_na) { |
| 33 | + if (is.atomic(i) && all(is.na(i))) { |
| 34 | + return(TRUE) |
| 35 | + } else if (.safe(all(is.na(i)), FALSE)) { |
| 36 | + return(TRUE) |
| 37 | + } |
| 38 | + } else if (length(i) == 0L || is.null(i)) { |
| 39 | + return(TRUE) |
| 40 | + } |
| 41 | + .is_null_string(i) |
| 42 | + }, |
| 43 | + FUN.VALUE = logical(1), |
| 44 | + USE.NAMES = FALSE |
| 45 | + ) |
| 46 | + x[!is_remove] |
33 | 47 | } |
34 | 48 |
|
35 | 49 | #' Remove empty strings from character |
|
0 commit comments