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
.
unlist(unname(list1))
# 1 2 2 3 4 4 5 6 6 6
# 1 2 3 4 5 6 7 8 9 10
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With