Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply two list objects in R [duplicate]

Tags:

list

r

operations

What I'm trying to do: Multiply an object in a list by another object in a different list? I need to multiply a vector of 1000 values in List A times a vector of 1000 values in List B.

For instance:

Vector in List_A:

1
2
3

Vector in List_B:

4
5
6

Output vector I want, List_A*B:

4
10
18

I found something called multiply.list() in the {lgcp} package but apparently not all the dependencies exist anymore so I can't use it...I tried using lapply(doesn't work, Error in x * l1 : non-numeric argument to binary operator) and mapply(which creates a matrix and doesn't just straight multiply the values).

I'm doing all of this within a loop, but cinput.data and l1 are both specified sections of a list.

#l2<-lapply(cinput.data, function(x) x*l1)

#l2<-mapply('*',cinput.data, l1)
like image 623
velociraptaco Avatar asked Jul 14 '16 15:07

velociraptaco


2 Answers

You could use the Map function. This keeps the list structure of the data too if you want it. If you don't you can simply use an unlist:

Map('*',l1,l2)

[[1]]
[1] 4

[[2]]
[1] 10

[[3]]
[1] 18

Data:

l1<-list(1,2,3)

l2<-list(4,5,6)
like image 96
Mike H. Avatar answered Sep 19 '22 10:09

Mike H.


On the basis that you're multiplying the lists together in the code snippet you provided, I'm going to assume that the lists only contain the vectors you want to multiple. I'd probably comment to clarify this point, but I don't have the rep.

Have you tried just "unlisting"?

unlist(cinput.data)*unlist(l1)

It's far from sophisticated, but from the details you've given alone I don't see why it won't do what you want.

like image 35
Ian_Fin Avatar answered Sep 22 '22 10:09

Ian_Fin