如何使用lapply()获取列表中每个元素的名称? [英] How to get the name of each element of a list using lapply()?

查看:89
本文介绍了如何使用lapply()获取列表中每个元素的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下我有以下列表

> test <- list("a" = 1, "b" = 2)

列表中的每个元素都有一个名称:

Each element of the list has a name :

> names(test)

现在,我想使用lapply()提取该名称,因为我想在将使用lapply调用的新函数中使用该名称.我只是不知道如何提取每个元素的名称.

Now, I want to extract that name using lapply() because I want to use it in a new function which will be called using lapply. I just don't know how to extract the name of each element.

我尝试使用deparse()substitute(),但结果很奇怪:

I've tried using deparse() and substitute() but the outcome is weird :

> lapply(test, function(x) {deparse(substitute(x))})
$a
[1] "X[[i]]"

$b
[1] "X[[i]]"

有人知道吗?

我想做这样的事情: 我有一个类似于test的列表:

I want to do something like this : I have a list which is like test :

> test <- list("a" = matrix(1, ncol = 3), "b" = matrix(2, ncol = 3))

我想对该列表应用一个函数,该函数可以转换每个元素内的数据并为每个列指定一个特定的名称:

I want to apply a function to that list which transform the data inside each element and give a specific name for each column :

make_df <- function(x) {
  output <- data.frame(x)
  names(output) <- c("items", "type", NAME_OF_X)
  return(output)
}
lapply(test, make_df)

预期输出为:

> test
$a
     [,1] [,2] [,3]
[1,]    1    1    1
attr(,"names")
[1] "index" "type"  "a"    

$b
     [,1] [,2] [,3]
[1,]    2    2    2
attr(,"names")
[1] "index" "type"  "b"    

我不知道如何获取元素名称来为第三列命名.

I don't know how I can get the name of the element to give a name to my third column.

推荐答案

以下是使用purrr的解决方案.它的运行速度似乎比aaronwolden的解决方案要快,但比akrun的解决方案要慢(如果重要的话):

Here's a solution using purrr. It seems to run faster than the solution by aaronwolden but slower than akrun's solution (if that's important):

library(purrr)
map2(test, names(test), function(vec, name) {
    names(vec) <- c("index", "type", name)
    return(vec)
})

$a
     [,1] [,2] [,3]
[1,]    1    1    1
attr(,"names")
[1] "index" "type"  "a"    

$b
     [,1] [,2] [,3]
[1,]    2    2    2
attr(,"names")
[1] "index" "type"  "b"    

这篇关于如何使用lapply()获取列表中每个元素的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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