DanStu
DanStu

Reputation: 174

Accessing list entries by name in a loop

I have a list where each entry is a vector of named integers, like this.

a = c(1:5)
b = c(2:6)
names(a) = c("a","b","c","d","e")
names(b) = c("b","c","d","e","f")
mylist <- list("0" = a, "1" = b)

The names inside list "mylist" will always start at "0" and increase by 1, but in my real scenario, the list will not always have two entries (can vary from 2 to a few dozen). What I am trying to do is loop through all names in my list (in this case "0" and "1"), and access the information corresponding to each index. I've tried

for (x in 0:(length(mylist) - 1)) {
    print(mylist$x)
}

and

for (x in 0:(length(mylist) - 1)) {
    name = as.character(x)
    print(mylist$name)
}

which also does not work. I'm aware that I can use normal list indexing such as

mylist[x]

but this includes the names (e.g. "0", "1") which I am trying to provide producing in the output. To clarify, I want my output to look like

print(mylist$"0")

output:

a b c d e 
1 2 3 4 5 

and not

print(mylist[1])

output:

$`0`
a b c d e 
1 2 3 4 5 

Upvotes: 1

Views: 32

Answers (1)

akrun
akrun

Reputation: 886988

If we want to show similar to $, use [[

mylist[[1]]

for (x in 0:(length(mylist) - 1)) {
    name = as.character(x)
    print(mylist[[name]])
}
#a b c d e 
#1 2 3 4 5 
#b c d e f 
#2 3 4 5 6 

Upvotes: 1

Related Questions