将R中的两个列表对象相乘 [英] Multiply two list objects in R

查看:90
本文介绍了将R中的两个列表对象相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做的事情: 将列表中的一个对象与另一个列表中的另一个对象相乘?我需要将列表A中1000个值的向量乘以列表B中1000个值的向量.

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.

例如:

List_A中的向量:

Vector in List_A:

1
2
3

List_B中的向量:

Vector in List_B:

4
5
6

我想要的输出向量,List_A * B:

Output vector I want, List_A*B:

4
10
18

我在{lgcp}包中找到了一个名为multipli.list()的东西,但是显然不是所有的依赖项都存在了,所以我不能使用它...我尝试使用lapply(不起作用,x中的错误* l1:二进制运算符的非数字参数)和mapply(这将创建矩阵,而不仅仅是将值直接相乘).

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).

我正在循环内完成所有这些操作,但是cinput.data和l1都是列表的指定部分.

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)

推荐答案

您可以使用Map函数.如果需要,也可以保留数据的列表结构.如果不这样做,您可以简单地使用unlist:

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

数据:

l1<-list(1,2,3)

l2<-list(4,5,6)

这篇关于将R中的两个列表对象相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆