mmann1123
mmann1123

Reputation: 5305

Call list by name from loop or lapply, in R

I am trying to use the output of a 'by' call which is easily converted to a list... but lists still defy me sometimes

a = list('1'=c(19,3,4,5), '4'=c(3,5,3,2,1,6), '8'=c(1,3))

 for (i in c(1,8,4)){
    # would like to do something like this
     a[["i"]]      # calling list elements by name rather than # 
     }


 #ideally the output would be something like this

>19,3,4,5 
>1,3
>3,5,3,2,1,6

Upvotes: 2

Views: 4418

Answers (3)

Marek
Marek

Reputation: 50763

You could loop over list without indexing:

for (ai in a) {
    print(ai)
}

It's good unless you need name of the element.

Upvotes: 1

Brian Diggs
Brian Diggs

Reputation: 58855

If you are just looping over the elements of the list to do something with each element (I realize you example is simplified), then consider the apply family of functions which do just this:

lapply(a, print)

Things get printed twice when entered interactively because they are printed inside the lapply, and then the return value of lapply is printed.

Upvotes: 2

Joshua Ulrich
Joshua Ulrich

Reputation: 176718

List names must character strings; they cannot be numbers. You need to convert i to a character string. You can use as.character or paste and you can do it at the initiation of the loop or inside it.

a = list('1'=c(19,3,4,5), '4'=c(3,5,3,2,1,6), '8'=c(1,3))

# convert inside loop
for (i in c(1,8,4)) {
  print(a[[as.character(i)]])
}
# convert at initiation
for (i in as.character(c(1,8,4))) {
  print(a[[i]])
}

Upvotes: 5

Related Questions