在lapply函数中访问和保留列表名称 [英] Access and preserve list names in lapply function
问题描述
我需要访问lapply函数中的列表名称.我在网上找到了一些线程,据说我应该遍历列表的名称,以便能够获取函数中的每个列表元素名称:
I need to access list names inside the lapply function. I've found some threads online where it's said I should iterate through the names of the list to be able to fetch each list element name in my function:
> n = names(mylist)
> mynewlist = lapply(n, function(nameindex, mylist) { return(mylist[[nameindex]]) }, mylist)
> names(mynewlist)
NULL
> names(mynewlist) = n
问题是mynewlist丢失了原始的mylist索引,我必须添加lastname()分配来恢复它们.
The problem is that mynewlist loses the original mylist indexes and I have to add that last names() assignment to restore them.
是否可以为lapply函数返回的每个元素赋予明确的索引名称?或者以其他方式确保mynewlist元素设置了正确的索引名称?我感觉如果lapply不按与mylist相同的顺序返回列表元素,则mynewlist索引名称可能是错误的.
Is there a way to give an explicit index name to each element returned by the lapply function? Or a different way to make sure mynewlist elements have the correct index names set? I feel mynewlist index names could be wrong if lapply does not return the list elements in the same order than mylist.
推荐答案
我相信默认情况下,lapply
保留要迭代的名称属性.当您将myList
的名称存储在n
中时,该向量不再具有任何名称".因此,如果您通过将其添加回去,
I believe that lapply
by default keeps the names attribute of whatever you are iterating over. When you store the names of myList
in n
, that vector no longer has any "names". So if you add that back in via,
names(n) <- names(myList)
并像以前一样使用lapply
,您应该会得到所需的结果.
and the use lapply
as before, you should get the desired result.
修改
今天早上我的大脑有点迷雾.这是另一个也许更方便的选择:
My brains a bit foggy this morning. Here's another, perhaps more convenient, option:
sapply(n,FUN = ...,simplify = FALSE,USE.NAMES = TRUE)
我一直在摸索,困惑于lapply
没有USE.NAMES
参数,然后我实际上查看了sapply
的代码,意识到我很傻,这可能是一种更好的方法去.
I was groping about, confused that lapply
didn't have a USE.NAMES
argument, and then I actually looked at the code for sapply
and realized I was being silly, and this was probably a better way to go.
这篇关于在lapply函数中访问和保留列表名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!