Using lapply with changing arguments

前端 未结 2 1603
醉酒成梦
醉酒成梦 2020-12-05 12:41

R textbooks continue to promote the use of lapply instead of loops. This is easy even for functions with arguments like

lapply(somelist, f, a=1, b=2) 
         


        
2条回答
  •  隐瞒了意图╮
    2020-12-05 13:00

    You just need to work out what to lapply() over. Here the names() of the lists suffices, after we rewrite f() to take different arguments:

    somelist <- list(USA = 1:10, Europe = 21:30,
                     Switzerland = seq(1, 5, length = 10))
    anotherlist <- list(USA = list(a = 1, b = 2), Europe = list(a = 2, b = 4),
                        Switzerland = list(a = 0.5, b = 1))
    
    f <- function(x, some, other) {
        (some[[x]] + other[[x]][["a"]]) * other[[x]][["b"]]
    }
    
    lapply(names(somelist), f, some = somelist, other = anotherlist)
    

    Giving:

    R> lapply(names(somelist), f, some = somelist, other = anotherlist)
    [[1]]
     [1]  4  6  8 10 12 14 16 18 20 22
    
    [[2]]
     [1]  92  96 100 104 108 112 116 120 124 128
    
    [[3]]
     [1] 1.500000 1.944444 2.388889 2.833333 3.277778 3.722222 4.166667 4.611111
     [9] 5.055556 5.500000
    

提交回复
热议问题