Search code examples
rlistloopsnested-lists

Loop over first list in a list of lists/nested list - R


I am new to R. I normally use Python. Let's say I have a list of 100 items. Each item is a list of 3 items. This is the data structure.

List > Companies > Date, Revenues, Expenses

I can retrieve information using:

list$companyA$revenue

I want to iterate through the 100 companies.

When I used this code, I end up getting everything printed:

for(i in 1:length(list)) {    
  print(list[i])             
}

I have also tried:

lapply(list, `[[`, 1)

This gives the 100 companies and the first list item, the date.

I want to put this information into a function:

Function(list$company[1])

And I want to iterate through each company, so I can automatically do

Function(list$companyA[1])
Function(list$companyB[1])
etc

I can't seem to find the right answer. Maybe I am searching for it in the wrong way.

EDIT: To be clear, I want a list of the companies, so I can iterate through the companies.

EDIT2: Here is an example data:

Company     Date         Revenues   Expenses
A           08012022     100        100
A           08022022     102        100
B           08012022     200        150
B           08012022     202        150

To get it into a list of lists, I used

list <- lapply(split(clean, clean$Company), as.list)

Now, from my understanding of Python, I want a list of my companies,so I can iterate through them and put them in a function:

firms = ("A, B")

So I can iterate through each company and replace it in the function.

My thought is then to have something like (again from Python):

for (firm in firms) {
Function(list$firm[2], list$firm[3])
}

Solution

  • You could use names() to extract the list names, and iterate them in the loop.

    firms <- names(list)
    
    for (firm in firms) {
      Function(list[[firm]][2], list[[firm]][3])
    }
    

    Note that you cannot use list$firm in the for loop. The $ works only if list has an element named firm. In the loop you should use list[[firm]].