It is possible to flatten lists of lists using unlist(list, recursive = FALSE)
, as was shown in this question. This action concatenates list names using the default dot (.
) separator, which is standard for variable naming in R. A simple example illustrates this:
# Create example list, l
> l <- list("a" = list("x" = 1, "y" = 2), "b" = list("x" = 3, "y" = 4))
> l
$a
$a$x
[1] 1
$a$y
[1] 2
$b
$b$x
[1] 3
$b$y
[1] 4
# Unlist lists in l
> l.unlisted <- unlist(l, recursive = FALSE)
> l.unlisted
$a.x
[1] 1
$a.y
[1] 2
$b.x
[1] 3
$b.y
[1] 4
In spite of the standard naming convention, I want the names to have a different separator (_
). It is possible to do this through string manipulation by using sub
to find and replace the default .
separator in each name after concatenation has already taken place once in unlist()
, as follows:
> names(l.unlisted) <- sub('.', '_', names(l.unlisted), fixed=TRUE)
> l.unlisted
$a_x
[1] 1
$a_y
[1] 2
$b_x
[1] 3
$b_y
[1] 4
While this would be sufficient in most situations, I think that the extra concatenation step can be eliminated by altering the default separator used by unlist()
. I hypothesize that this can be done by altering the source code of the function using fix()
by adding a sep
argument similar to the the one used in paste()
. However, I do not know how to do so, as unlist()
is an internal function.
Is there a way to alter the default name concatenation separator in unlist()
, and how can this be done?