在 FUN 中访问 lapply 索引名称 [英] Access lapply index names inside FUN

查看:29
本文介绍了在 FUN 中访问 lapply 索引名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在我的 lapply() 函数中获取列表索引名称?

Is there a way to get the list index name in my lapply() function?

n = names(mylist)
lapply(mylist, function(list.elem) { cat("What is the name of this list element?
" })

我问过之前是否可以保留lapply() returned 列表中的索引名称,但我仍然不知道是否有一种简单的方法来获取自定义函数中的每个元素名称.我想避免对名称本身调用 lapply,我宁愿在函数参数中获取名称.

I asked before if it's possible to preserve the index names in the lapply() returned list, but I still don't know if there is an easy way to fetch each element name inside the custom function. I would like to avoid to call lapply on the names themselves, I'd rather get the name in the function parameters.

推荐答案

不幸的是,lapply 只给你你传递给它的向量的元素.通常的解决方法是将向量的名称或索引而不是向量本身传递给它.

Unfortunately, lapply only gives you the elements of the vector you pass it. The usual work-around is to pass it the names or indices of the vector instead of the vector itself.

但请注意,您始终可以向函数传递额外的参数,因此以下内容有效:

But note that you can always pass in extra arguments to the function, so the following works:

x <- list(a=11,b=12,c=13) # Changed to list to address concerns in commments
lapply(seq_along(x), function(y, n, i) { paste(n[[i]], y[[i]]) }, y=x, n=names(x))

这里我在x的索引上使用了lapply,但也传入了xx.如您所见,函数参数的顺序可以是任意的 - lapply 会将元素"(这里是索引)传递给第一个参数 not额外的.在本例中,我指定了 yn,所以只剩下 i...

Here I use lapply over the indices of x, but also pass in x and the names of x. As you can see, the order of the function arguments can be anything - lapply will pass in the "element" (here the index) to the first argument not specified among the extra ones. In this case, I specify y and n, so there's only i left...

产生以下结果:

[[1]]
[1] "a 11"

[[2]]
[1] "b 12"

[[3]]
[1] "c 13"

UPDATE 更简单的例子,结果相同:

UPDATE Simpler example, same result:

lapply(seq_along(x), function(i) paste(names(x)[[i]], x[[i]]))

这里的函数使用全局"变量 x 并在每次调用中提取名称.

Here the function uses "global" variable x and extracts the names in each call.

这篇关于在 FUN 中访问 lapply 索引名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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