使用循环在 R 中的列表中处理对象的名称和值

Working with names and values of objects in a list in R using loops

如何在循环中检索列表对象的名称。我想做这样的事情:

lst = list(a = c(1,2), b = 1)

for(x in lst){
#print the name of the object x in the list
# print the multiplication of the values
}

期望的结果:

"a"
2 4
"b"
2

在 Python 中,可以使用字典并使用以下代码获得所需的结果:

lst = {"a":[1,2,3], "b":1} 

for key , value in lst.items():
   print(key)
   print(value * 2)

但由于在 R 中我们没有字典数据结构,我试图使用列表来实现这一点,但我不知道如何 return 对象名称。任何帮助将不胜感激。

我们可以直接得到names

names(lst)
[1] "a" "b"

或者如果我们想在一个循环中print,循环遍历 list 的序列或 namesprint 的名称,以及值通过根据名称 multiplied

提取列表元素得到
for(nm in  names(lst)) {
     print(nm)
     print(lst[[nm]] * 2)
  }
[1] "a"
[1] 2 4
[1] "b"
[1] 2

或者另一种选择是 iwalk

library(purrr)
iwalk(lst, ~ {print(.y); print(.x * 2)})
[1] "a"
[1] 2 4
[1] "b"
[1] 2