rlistlapplysapplyindices

Force lapply/sapply to index output list with inputs


As in the title, how to force lapply or sapply to use input vector values to index the output. I have two cases; let me begin with the simpler one. The following code

lapply(c('a', 'b'), function(idx){
    rnorm(1)
})

gives me the output

[[1]]
[1] -1.359386

[[2]]
[1] -0.3428958

but I would like to receive:

$a
[1] -1.359386

$b
[1] -0.3428958

In the final aim, my code looks like follows:

m = sapply(unique(isotopes[, 1]), function(el){
    sapply(isotopes[isotopes$element == el, 2], function(mnr){
        isotopes[isotopes$element == el & isotopes$mass_nr == mnr, 3]
    })
})

and it gives me outputs like

$Pu
[1] 238.0496 239.0522 240.0538 241.0569 242.0587 244.0642

while I would like to obtain list of lists, to be able to use m['Pu'][240] or m['Pu']['240'] etc. (for 'Pu' isotopes[isotopes$element == el, 2] is a vector of 238 239 240 241 242 244)

PS. Of course, I can use

m = function(el, mnr){ isotopes[isotopes$element == el & isotopes$mass_nr == mnr, 3] }

but I'm interested if the above problem possesses a neat solution :)


Solution

  • You could try

    lapply(c(a = "a", b = "b"), function(idx) {
        rnorm(1)
    })
    

    which should give the desired output

    $a
    [1] 1.556433
    
    $b
    [1] -0.2282002