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

Time:05-05

how do you retrieve the names of the objects of a list in a loop. I want to do something like this:

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
}

Desired results:

"a"
2 4
"b"
2

In Python one can use dictionary and with the below code get the desired results:

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

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

but since in R we have no dictionary data structure, I am trying to achieve this using lists but I don't know how to return the objects names. Any help would be appreciated.

CodePudding user response:

We can get the names directly

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

Or if we want to print in a loop, loop over the sequence or names of the list, print the name, as well as the value got by extracting the list element based on the name multiplied

for(nm in  names(lst)) {
     print(nm)
     print(lst[[nm]] * 2)
  }
[1] "a"
[1] 2 4
[1] "b"
[1] 2

Or another option is iwalk

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