How to combine rapply() and mapply(), or how to use mapply/Map recursively?

前端 未结 2 557
庸人自扰
庸人自扰 2021-01-06 05:21

I was wondering if there\'s a simple way to combine the functions of rapply( , how = \"replace\") and mapply(), in order to use mapply()

2条回答
  •  情歌与酒
    2021-01-06 05:35

    Or you can write a recursive function combined with Map to achieve this, which works as long as A and B have the same structure:

    s <- function(x, y) tryCatch(x + y, error = function(e) Map(s, x, y))
    s(A, B)
    
    [[1]]
    [[1]][[1]]
    [1] 2 4 6
    
    [[1]][[2]]
    [1] 4 6 8
    
    
    [[2]]
    [[2]][[1]]
    [1] 8 6 4
    
    [[2]][[2]]
    [1] 6 4 2
    

    Not sure if you can use rapply in this case, which loops through a single list recursively. But in order to loop through two lists recursively at the same time, you need a higher level of recursion? Am I wrong?

提交回复
热议问题