rose
rose

Reputation: 1981

Create a list from matrix in R

I have two lists v and w and I would like to create again a list z from matrix M . How can I do this in R?

    v = list(a = c(1, 5), b = 2, c= 3)
    w = list( a= c(2, 10), b = 4, c = 6)
    M  =  as.matrix(unlist( v) * unlist(w))
    > M
        [,1]
    a1    2
    a2   50
    b     8
    c    18
    z = list(a = c(2, 50), b = 8, c = 18)

Upvotes: 0

Views: 120

Answers (2)

flodel
flodel

Reputation: 89057

Do it like this:

mapply(`*`, v, w)

Upvotes: 3

Ferdinand.kraft
Ferdinand.kraft

Reputation: 12819

Maybe you want z <- lapply(1:length(v), function(i) v[[i]]*w[[i]])? Add names(z) <- names(v) to keep the names.

Upvotes: 2

Related Questions