R 如何使用lappy()获取列表中每个元素的名称?
假设我有下面的列表R 如何使用lappy()获取列表中每个元素的名称?,r,lapply,R,Lapply,假设我有下面的列表 > test <- list("a" = 1, "b" = 2) 现在,我想使用lappy()提取该名称,因为我想在将使用lappy调用的新函数中使用它。我只是不知道如何提取每个元素的名称 我试过使用deparse()和substitute()但结果很奇怪: > lapply(test, function(x) {deparse(substitute(x))}) $a [1] "X[[i]]" $b [1] "X[[i]]" 有人有线索吗 精度: 我想
> test <- list("a" = 1, "b" = 2)
现在,我想使用lappy()
提取该名称,因为我想在将使用lappy调用的新函数中使用它。我只是不知道如何提取每个元素的名称
我试过使用deparse()
和substitute()
但结果很奇怪:
> lapply(test, function(x) {deparse(substitute(x))})
$a
[1] "X[[i]]"
$b
[1] "X[[i]]"
有人有线索吗
精度:
我想这样做:
我有一个类似于测试的列表:
> test <- list("a" = matrix(1, ncol = 3), "b" = matrix(2, ncol = 3))
我不知道如何获取元素的名称,以便为我的第三列命名。假设您的意思是让
test
的两个元素都包含一个三列矩阵,您可以使用mapply()
分别提供列表和列表的名称:
test <- list("a" = matrix(1, ncol = 3), "b" = matrix(2, ncol = 3))
make_df <- function(x, y) {
output <- data.frame(x)
names(output) <- c("items", "type", y)
return(output)
}
mapply(make_df, x = test, y = names(test), SIMPLIFY = FALSE)
更新
要实现您在更新的问题中描述的预期输出:
test.names <- lapply(names(test), function(x) c("index", "type", x))
Map(setNames, test, test.names)
根据所显示的预期产量
make_attr_names <- function(x){
x1 <- test[[x]]
attr(x1, 'names') <- c('items','type', x)
x1}
lapply(names(test), make_attr_names)
#[[1]]
# [,1] [,2] [,3]
#[1,] 1 1 1
#attr(,"names")
#[1] "items" "type" "a"
#[[2]]
# [,1] [,2] [,3]
#[1,] 2 2 2
#attr(,"names")
#[1] "items" "type" "b"
make_attr_names这里有一个使用purrr
的解决方案。它的运行速度似乎比aaronwolden的解决方案快,但比akrun的解决方案慢(如果这很重要):
库(purrr)
map2(测试,名称(测试),函数(vec,名称){
名称(vec)尝试使用lappy(名称(测试),函数(x)测试[[x]])
通过循环使用名称
,您可以选择获取值以及键或lappy(seq_-along(测试),函数(i)名称(测试[i])
好的,第二个可以工作,但我想要与列表一起工作的东西,而不是seq_-along()
@PAC I展示了获取值的方法,但是如果您只需要键lappy(名称(test),函数(x)x)
则需要获取列表元素的名称,并且链接看起来像是您想要的重复
test <- list("a" = matrix(1, ncol = 3), "b" = matrix(2, ncol = 3))
make_df <- function(x, y) {
output <- data.frame(x)
names(output) <- c("items", "type", y)
return(output)
}
mapply(make_df, x = test, y = names(test), SIMPLIFY = FALSE)
## $a
## items type a
## 1 1 1 1
##
## $b
## items type b
## 1 2 2 2
test.names <- lapply(names(test), function(x) c("index", "type", x))
Map(setNames, test, test.names)
## $a
## [,1] [,2] [,3]
## [1,] 1 1 1
## attr(,"names")
## [1] "a" "index" "type"
##
## $b
## [,1] [,2] [,3]
## [1,] 2 2 2
## attr(,"names")
## [1] "b" "index" "type"
make_attr_names <- function(x){
x1 <- test[[x]]
attr(x1, 'names') <- c('items','type', x)
x1}
lapply(names(test), make_attr_names)
#[[1]]
# [,1] [,2] [,3]
#[1,] 1 1 1
#attr(,"names")
#[1] "items" "type" "a"
#[[2]]
# [,1] [,2] [,3]
#[1,] 2 2 2
#attr(,"names")
#[1] "items" "type" "b"
make_df <- function(x){
setNames(as.data.frame(test[[x]]), c('items', 'type', x))}
lapply(names(test), make_df)
#[[1]]
# items type a
#1 1 1 1
#[[2]]
# items type b
#1 2 2 2
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"