Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
930 views
in Technique[技术] by (71.8m points)

list - R unlist changes names

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...