Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

applying a function to lists within a list

Tags:

r

lapply

I would like to apply a function to lists within a list. The second-level lists consist of an arbitrary number of strings (which is why, in less I am missing something, the list-within-list data structure is the most appropriate). I would like to know what the most efficient way to do this is. Here's a simple example that accomplishes what I want with a loop:

#sample data
set.seed(12345)
mylist <- list()
mylist[[1]] <- list(sample(letters,3),sample(letters,4),sample(letters,5))
mylist[[2]] <- list(sample(letters,4),sample(letters,5))
mylist[[3]] <- list(sample(letters,5),sample(letters,3),sample(letters,4),sample(letters,2)

#working loop example
result <- list()
for(i in 1:length(mylist)){
  result[[i]] <- lapply(mylist[[i]],function(x,l) 0  + (l %in% x),l=letters)
}

Is there a simple way to turn this loop into a one-line solution?

The broader context of this is that I want to then reduce the data in result further, for example (in this simple case) by adding up to get the number of times each letter occurs over i, or the original dimension of mylist. So the final goal is something like:

final.result <- lapply(result,Reduce,f='+')

So an alternative might be to simply apply the function to unlist(mylist) and then somehow restore the i information to the resulting data structure...this seems more complicated to me but I'm open to suggestions.

like image 415
tvg Avatar asked Apr 15 '26 16:04

tvg


1 Answers

You can use the recursive ?rapply with argument how='list' to keep the list structure and then wrap Reduce to get your final result:

lapply(rapply(mylist,function(x) letters %in% x + 0, how='list'), Reduce, f='+')

Your function can be shortened using letters as pointed out by Colonel Beauvel.

like image 59
user1981275 Avatar answered Apr 18 '26 05:04

user1981275



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!