想象一下我有以下列表:
> test <- list("a" = 1, "b" = 2)
列表中的每个元素都有一个名称:
> names(test)
现在,我想使用lapply()
来提取该名称,因为我想将其用于新函数中,该函数将使用lapply调用。 我只是不知道如何提取每个元素的名称。
我尝试过使用deparse()
和substitute()
,但结果很奇怪:
> lapply(test, function(x) {deparse(substitute(x))})
$a
[1] "X[[i]]"
$b
[1] "X[[i]]"
有人知道吗?
精度:
我想做这样一件事情: 我有一个名为test的列表:
> test <- list("a" = matrix(1, ncol = 3), "b" = matrix(2, ncol = 3))
我想对该列表应用一个函数,将每个元素中的数据进行转换,并为每列指定一个特定的名称:
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"
我不知道如何获取元素的名称,以便为我的第三列命名。
lapply(names(test), function(x) test[[x]])
来循环遍历。使用names
循环遍历时,你可以同时获得键和值的选项。 - akrunseq_along()
。 - PAClapply(names(test), function(x) x)
。 - akrun