问题
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