Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R unlist changes names

Tags:

list

r

Given the following list:

l <- list("foo123"=c(1:3), "foo456"=5, "foo789"=8)
print(l)
#  $foo123
#  [1] 1 2 3
#  
#  $foo456
#  [1] 5
#  
#  $foo789
#  [1] 

When I unlist() the list, the names get integers appended if they are duplicates.

unlist(l)
#  foo1231 foo1232 foo1233  foo456  foo789 
#        1       2       3       5       8 

I would like to preserve names, so use.names=FALSE is not ideal. Is this behaviour explained anywhere in the help page? Can it be modified?

Can unlist be configured to preserve names so that my result is:

#  foo123 foo123 foo123 foo456 foo789 
#       1      2      3      5      8
like image 547
Megatron Avatar asked Feb 02 '16 20:02

Megatron


People also ask

What does unlist () do in R?

unlist() Usage Use unlist() function to convert a list to a vector by unlisting the elements from a list. A list in R contains heterogeneous elements meaning can contain elements of different types whereas a vector in R is a basic data structure containing elements of the same data type.

What is the use of unlist () function?

unlist() function in R Language is used to convert a list to vector. It simplifies to produce a vector by preserving all components.


2 Answers

This doesn't exactly answer your question, but an alternative that you can consider would be to go from a list to a "long" data.frame or data.table.

This is easily achieved with stack in base R or melt from "reshape2" or "data.table".

Example:

stack(l)
#   values    ind
# 1      1 foo123
# 2      2 foo123
# 3      3 foo123
# 4      5 foo456
# 5      8 foo789

library(data.table)
melt(l)
#   value     L1
# 1     1 foo123
# 2     2 foo123
# 3     3 foo123
# 4     5 foo456
# 5     8 foo789

Then, if you really wanted a named vector, you could always do:

o <- data.table::melt(l)
setNames(o$value, o$L1)
# foo123 foo123 foo123 foo456 foo789 
#      1      2      3      5      8 
like image 114
A5C1D2H2I1M1N2O1R2T1 Avatar answered Nov 16 '22 03:11

A5C1D2H2I1M1N2O1R2T1


We can try setting the names after unlisting. We also use use.names=FALSE to avoid creating and rewriting a vector of names (MartinMorgan):

setNames(unlist(l, use.names=F),rep(names(l), lengths(l)))
#foo123 foo123 foo123 foo456 foo789 
#     1      2      3      5      8

However, note that in most cases, duplicate names will lead to ambiguity and possibly errors. Given your example, if we now attempt to subset using the name "foo123" R outputs only the first instance:

o <- setNames(unlist(l, use.names=F),rep(names(l), lengths(l)))
o["foo123"]
#  foo123
#       1
like image 36
Pierre L Avatar answered Nov 16 '22 03:11

Pierre L