Multiplying Combinations of a list of lists in R

前端 未结 4 1485
孤城傲影
孤城傲影 2020-12-07 02:37

Given a list of two lists, I am trying to obtain, without using for loops, a list of all element-wise products of the first list with the second. For example:



        
4条回答
  •  南笙
    南笙 (楼主)
    2020-12-07 02:50

    # Your data
    a <- list(c(1,2), c(2,3), c(4,5))
    b <- list(c(1,3), c(3,4), c(6,2))
    
    # Matrix with indicies for elements to multiply
    G <- expand.grid(1:3,1:3)
    
    # Coversion of G to list
    L <- lapply(1:nrow(G),function(x,d=G) d[x,])
    
    lapply(L,function(i,x=a,y=b) x[[i[[2]]]]*y[[i[[1]]]])
    

提交回复
热议问题