Convert a list to an atomic vector if it consists solely of atomic elements of length 1.
Source:R/misc.utilities.R
simplify_simple.RdThis behaviour is not dissimilar to that of simplify2array(), but
it offers more robust handling of empty or NULL elements and never
promotes to a matrix or an array, making it suitable to be a column
of a data.frame.
Arguments
- x
an R
listto be simplified.- toNA
a character string indicating whether
NULLentries (if"null") or 0-length entries includingNULL(if"empty") should be replaced withNAs before attempting conversion; specifyingkeeporFALSEleaves them alone (typically preventing conversion).- empty
a character string indicating how empty lists should be handled: either
"keep", in which case they are unchanged or"unlist", in which cases they are unlisted (typically toNULL).- ...
additional arguments passed to
unlist().
Examples
(x <- as.list(1:5))
#> [[1]]
#> [1] 1
#>
#> [[2]]
#> [1] 2
#>
#> [[3]]
#> [1] 3
#>
#> [[4]]
#> [1] 4
#>
#> [[5]]
#> [1] 5
#>
stopifnot(identical(simplify_simple(x), 1:5))
x[3] <- list(NULL) # Put a NULL in place of 3.
x
#> [[1]]
#> [1] 1
#>
#> [[2]]
#> [1] 2
#>
#> [[3]]
#> NULL
#>
#> [[4]]
#> [1] 4
#>
#> [[5]]
#> [1] 5
#>
stopifnot(identical(simplify_simple(x, FALSE), x)) # Can't be simplified without replacing the NULL.
stopifnot(identical(simplify_simple(x), c(1L,2L,NA,4L,5L))) # NULL replaced by NA and simplified.
x[[3]] <- integer(0)
x
#> [[1]]
#> [1] 1
#>
#> [[2]]
#> [1] 2
#>
#> [[3]]
#> integer(0)
#>
#> [[4]]
#> [1] 4
#>
#> [[5]]
#> [1] 5
#>
stopifnot(identical(simplify_simple(x), x)) # A 0-length vector is not replaced by default,
stopifnot(identical(simplify_simple(x, "empty"), c(1L,2L,NA,4L,5L))) # but can be.
(x <- lapply(1:5, function(i) c(i,i+1L))) # Elements are vectors of equal length.
#> [[1]]
#> [1] 1 2
#>
#> [[2]]
#> [1] 2 3
#>
#> [[3]]
#> [1] 3 4
#>
#> [[4]]
#> [1] 4 5
#>
#> [[5]]
#> [1] 5 6
#>
simplify2array(x) # simplify2array() creates a matrix,
#> [,1] [,2] [,3] [,4] [,5]
#> [1,] 1 2 3 4 5
#> [2,] 2 3 4 5 6
stopifnot(identical(simplify_simple(x), x)) # but simplify_simple() returns a list.