Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid unlist() modification of list naming

Tags:

list

r

I am a bit puzzled by the names produced by unlist(). Please consider the following MWE

vector1 <- c(1,2,3,4,5,6,7,8,9,10)
names(vector1) <- c(1,2,2,3,4,4,5,6,6,6)
names(vector1)
# [1] "1" "2" "2" "3" "4" "4" "5" "6" "6" "6"
list1 <- split(vector1,names(vector1))
names(list1)
# [1] "1" "2" "3" "4" "5" "6"

but then

names(unlist(list1))
# [1] "1.1" "2.2" "2.2" "3.3" "4.4" "4.4" "5.5" "6.6" "6.6" "6.6"

According to the documentation of unlist()

By default, unlist tries to retain the naming information present in x.

so I can't make sense of this particular behaviour.

My problem is that the names as created by unlist() can't be matched against the names of the original vector1.

like image 566
CptNemo Avatar asked Apr 25 '14 01:04

CptNemo


2 Answers

unlist(unname(list1))
#  1  2  2  3  4  4  5  6  6  6 
#  1  2  3  4  5  6  7  8  9 10 
like image 158
Josh O'Brien Avatar answered Nov 05 '22 08:11

Josh O'Brien


I sympathize with your frustration. R is (I think) trying to retain both the information in names(x) and the information in the names of the original components (consider the results of unlist(setNames(list1,letters[1:6])), which makes the behaviour make more sense).

You can get what you want via

setNames(unlist(list1),unlist(lapply(list1,names)))

although it is admittedly awkward -- I would make this into an unlistWithNames function (or something sensibly named) if I wanted to do it often. PS @JoshOBrien's answer is simpler, but I will leave this here because it explains things a bit more.

like image 31
Ben Bolker Avatar answered Nov 05 '22 08:11

Ben Bolker