Search code examples
rloopsiterator

How to iterate over a list of lists in R?


I am new to R and not able to find the counter code in R for the following Python code. Please help

list1 = [10, 20] # or a tuple
list2 = [30, 40] # or a tuple
mylist = [list1, list2] # can be tuple of tuples also
for _list in mylist:
    a = _list[0]
    b = _list[1]
    # usage of a and b

I wrote the following R script:

list1 <- list(10, 20)
list2 <- list(30, 40)
mylist <- list(list1, list2)

for( j in 1:length(mylist))
{
    print(j)
    list1=mylist[[j]]
    print(list1)
    # Works perfect till here

    # Error in below lines
    a=list1[[0]]
    b=list1[[1]]
    # usage of a and b
}

Solution

  • In R, indexing starts from 1 and not 0 - difference between Python and R. So, if we change it to 1 and 2, it works. In addition, 1:length may be replaced with less buggy seq_along

    for( j in seq_along(mylist)){
        print(j)
        list1 = mylist[[j]]
        print(list1)    
        a=list1[[1]]
        b=list1[[2]]
        # usage of a and b
    }
    [1] 1
    [[1]]
    [1] 10
    
    [[2]]
    [1] 20
    
    [1] 2
    [[1]]
    [1] 30
    
    [[2]]
    [1] 40
    

    NOTE: list1, a, b are objects created within the loop and this gets updated in each iteration. It is not clear about the final outcome