简体   繁体   中英

index number of nested lapply

I'm trying to understand how to access the outer iteration index of a nested lapply function over 2 lists.

dummy case: lets say i have a list of 2 items here, and on of 3 items and use a nested lapply to make variables item1_x, item1_y, item1_z etc. In the code i'm working on I tried to access the iteration indices which I can do for the inner lapply with parent.frame()$i[], but how to also access the outer iteration index?

Goal: I want to print 1, 2 as the code goes through the outer lapply print 1, 2, 3 as the code goes through the inner lapply and thus be able to also print outer index times inner index, i,e 1,2,3,4,5,6

I was looking for a similar code piece as parent.frame()$i[] to access the outer iteration index (if that exists), also to better understand how that works, but honestly any other solution will be good of course

mylist <- c("item1", "item2")

  lapply(mylist, function(y) {
         lapply(c("x", "y", "z"), function(x) {
            print(parent.frame()$i[])
### access index number of outer lapply here somehow. 
###   index 1 * index 2 should be giving a print(...) of 1:6 than...

        })})

Here are a couple of approaches

Using mapply

mapply(function(y, z) {
                lapply(c("x", "y", "z"), function(x) {
                                            print(paste(y, x))
                                            print(z)
                                        })
        }, 
        mylist, 
        seq_along(mylist))

Or only lapply

lapply(seq_along(mylist),   function(y) {
                                lapply(c("x", "y", "z"), function(x) {
                                                            print(paste(mylist[y], x))
                                                        })
                            })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM