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

查看:113
本文介绍了在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?\n" })

我之前问过 是否可以保留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将"element"(此处为索引)传递给多余参数中指定的第一个参数 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 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天全站免登陆