是否有一种方法可以在我的lapply()函数中获得列表索引名?
n = names(mylist)
lapply(mylist, function(list.elem) { cat("What is the name of this list element?\n" })
我以前问过是否可以在lapply()返回的列表中保留索引名,但我仍然不知道是否有一种简单的方法来获取自定义函数中的每个元素名。我希望避免对名称本身调用lapply,我宁愿在函数参数中获得名称。
是否有一种方法可以在我的lapply()函数中获得列表索引名?
n = names(mylist)
lapply(mylist, function(list.elem) { cat("What is the name of this list element?\n" })
我以前问过是否可以在lapply()返回的列表中保留索引名,但我仍然不知道是否有一种简单的方法来获取自定义函数中的每个元素名。我希望避免对名称本身调用lapply,我宁愿在函数参数中获得名称。
当前回答
汤米的答案适用于命名向量,但我知道你对列表感兴趣。似乎他在绕一圈因为他引用了调用环境中的x。这个函数只使用传递给函数的参数,因此不假设传递对象的名称:
x <- list(a=11,b=12,c=13)
lapply(x, function(z) { attributes(deparse(substitute(z)))$names } )
#--------
$a
NULL
$b
NULL
$c
NULL
#--------
names( lapply(x, function(z) { attributes(deparse(substitute(z)))$names } ))
#[1] "a" "b" "c"
what_is_my_name <- function(ZZZ) return(deparse(substitute(ZZZ)))
what_is_my_name(X)
#[1] "X"
what_is_my_name(ZZZ=this)
#[1] "this"
exists("this")
#[1] FALSE
其他回答
我的答案与Tommy和caracals的方向相同,但避免了将列表保存为额外对象。
lapply(seq(3), function(i, y=list(a=14,b=15,c=16)) { paste(names(y)[[i]], y[[i]]) })
结果:
[[1]]
[1] "a 14"
[[2]]
[1] "b 15"
[[3]]
[1] "c 16"
这将列表作为FUN的命名参数(而不是lapply)。Lapply只需要遍历列表的元素(在更改列表长度时,要注意将第一个参数更改为Lapply)。
注意:将列表直接作为附加参数提供给lapply也可以:
lapply(seq(3), function(i, y) { paste(names(y)[[i]], y[[i]]) }, y=list(a=14,b=15,c=16))
汤米的答案适用于命名向量,但我知道你对列表感兴趣。似乎他在绕一圈因为他引用了调用环境中的x。这个函数只使用传递给函数的参数,因此不假设传递对象的名称:
x <- list(a=11,b=12,c=13)
lapply(x, function(z) { attributes(deparse(substitute(z)))$names } )
#--------
$a
NULL
$b
NULL
$c
NULL
#--------
names( lapply(x, function(z) { attributes(deparse(substitute(z)))$names } ))
#[1] "a" "b" "c"
what_is_my_name <- function(ZZZ) return(deparse(substitute(ZZZ)))
what_is_my_name(X)
#[1] "X"
what_is_my_name(ZZZ=this)
#[1] "this"
exists("this")
#[1] FALSE
这基本上使用了与Tommy相同的解决方法,但是使用Map(),不需要访问存储列表组件名称的全局变量。
> x <- list(a=11, b=12, c=13)
> Map(function(x, i) paste(i, x), x, names(x))
$a
[1] "a 11"
$b
[1] "b 12"
$c
[1] "c 13
或者,如果你喜欢mapply()
> mapply(function(x, i) paste(i, x), x, names(x))
a b c
"a 11" "b 12" "c 13"
同样的问题我已经遇到过很多次了…… 我开始用另一种方法…我不再使用lapply,而是开始使用mapply
n = names(mylist)
mapply(function(list.elem, names) { }, list.elem = mylist, names = n)
只需要把名字循环进去。
sapply(names(mylist), function(n) {
doSomething(mylist[[n]])
cat(n, '\n')
}