【问题标题】:How to get the names of the objects/get (k, v) pair while iterating a list?如何在迭代列表时获取对象/get(k,v)对的名称?
【发布时间】:2018-04-16 18:22:02
【问题描述】:

假设我创建了一个列表并为列表中的对象命名。

list = rep(0, times = 20)
list = lapply(list, initialize_list)
names(list) = names

现在我想遍历列表中的所有对象。我可以对对象执行任何操作,但我只是找不到同时获取对象名称的方法。这是否可以在for 循环或lapply 调用中实现而无需显式编写

for (name in names(myList)) {
    v = myList[[name]]
    ...
}

?

现有的答案似乎并不是我想要的,我似乎只找到了一个相关的blog post,它提供了上述看似笨拙的解决方案。

【问题讨论】:

  • 你可以使用purrr::imap,大致相当于Map(function(.x, .y){...}, .x = some_iterable, .y = names(some_iterable))(或者直接使用Map

标签: r list loops iterator iteration


【解决方案1】:

您可以只使用名称的索引。

lst = rep(0, times = 20)
lst = lapply(lst, sum)
names(lst) = letters[1:20]
for (id in seq_along(names(lst))) {
  v = names(lst)[id]
}

【讨论】:

    猜你喜欢
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-17
    • 2016-02-08
    • 1970-01-01
    • 2010-12-05
    • 2016-09-03
    相关资源
    最近更新 更多