r - Given an element of a list, how do I recover its index inside the list? -


my problem this:

i have list, l, each element matrix of same dimension. need multiply each matrix inside list corresponding element in outside vector h, , sum matrices.

set.seed(101) l <- replicate(3,matrix(rnorm(4),2),simplify=false) h <- 2:4  # need l[[1]]*h[1] + l[[2]]*h[2] +l[[3]]*h[3] 

given need experiment different number of matrices, , have bunch of them, i've got in smart way. idea was

l1 <- lapply(l, function(x) x*h[x]) l2 <- reduce('+', l1) 

where "h[x]" indexing vector h index of matrix x inside list l, get

 l1 = list(l[[1]]*h[1], l[[2]]*h[2], l[[3]]*h[3]) 

so, question is, how index of element in list using element itself? h[l[[m1]]] h[1].

or, if got other way of solving problem, how do it?

i think you're looking mapply()/map() (map easier here because doesn't try simplify results):

?map:

‘map’ applies function corresponding elements of given vectors ... ‘map’ simple wrapper ‘mapply’ not attempt simplify result ...

?mapply:

‘mapply’ applies ‘fun’ first elements of each ... argument, second elements, third elements, , on

set example:

set.seed(101) l <- replicate(3,matrix(rnorm(4),2),simplify=false) h <- 2:4 

do it:

reduce("+",map("*",l,h)) 

Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -