取消列出更改名称 [英] R unlist changes names

查看:66
本文介绍了取消列出更改名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下列表:

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

当我unlist()列表时,如果名称重复,则名称后面会附加整数.

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 

我想保留名称,所以use.names=FALSE是不理想的.在帮助页面的任何位置都可以解释此行为吗?可以修改吗?

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

推荐答案

我们可以在取消列出后尝试设置名称.我们还使用use.names=FALSE避免创建和重写名称的向量(MartinMorgan):

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

但是,请注意,在大多数情况下,重复的名称将导致模棱两可,甚至可能导致错误.以您的示例为例,如果我们现在尝试使用名称"foo123"进行子集设置,R仅输出第一个实例:

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

这篇关于取消列出更改名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆