Multiply two list objects in R [duplicate]

青春壹個敷衍的年華 提交于 2019-12-07 07:32:45

问题


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)

回答1:


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)



回答2:


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.




回答3:


I think that you just want to multiply the numbers in the lists together:

> ListA <- list(1,2,3)
> ListB <- list(4,5,6)
> ListAB <- list(unlist(ListA)*unlist(ListB))
> ListAB
[[1]]
[1]  4 10 18

Referring to lists as "vectors" in R is confusing since "vector" has another meaning in R



来源:https://stackoverflow.com/questions/38378143/multiply-two-list-objects-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!