简体   繁体   English

名称与列表名称相同的字符向量

[英]name character vectors with same name of list

I have a list that looks like this. 我有一个看起来像这样的列表。

my_list <- list(Y = c("p", "q"), K = c("s", "t", "u"))

I want to name each list element (the character vectors) with the name of the list they are in. All element of the same vector must have the same name 我想用它们所在列表的名称命名每个列表元素(字符向量)。同一向量的所有元素必须具有相同的名称

I was able to write this function that works on a single list element 我能够编写适用于单个列表元素的此函数

name_vector <- function(x){
      names(x[[1]]) <- rep(names(x[1]), length(x[[1]]))
      return(x)
    }

> name_vector(my_list[1])
$Y
  Y   Y 
"p" "q" 

But can't find a way to vectorize it. 但无法找到一种矢量化的方法。 If I run it with an apply function it just returns the list unchanged 如果我使用apply函数运行它,它只会返回列表不变

> lapply(my_list, name_vector)
$K
[1] "p" "q"

$J
[1] "x" "y"

My desired output for my_list is a named vector 我想要的my_list输出是一个命名向量

 Y   Y   K   K   K  
"p" "q" "s" "t" "u"

We unlist the list while setting the names by rep licating 我们unlistlist ,同时设置由名rep licating

setNames(unlist(my_list), rep(names(my_list), lengths(my_list)))

Or stack into a two column data.frame, extract the 'values' column and name it with 'ind' 或者stack成两列data.frame,提取'values'列并用'ind'命名

with(stack(my_list), setNames(values, ind))

if your names don't end with numbers : 如果你的名字不以数字结尾:

vec <- unlist(my_list)
names(vec) <- sub("\\d+$","",names(vec))
vec                
#   Y   Y   K   K   K 
# "p" "q" "s" "t" "u" 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM